On Dec 19, 2017, at 18:32 , Jeremy Hughes <moon.rab...@virginmedia.com> wrote:
> 
>> On 20 Dec 2017, at 02:22, Jeremy Hughes <moon.rab...@virginmedia.com 
>> <mailto:moon.rab...@virginmedia.com>> wrote:
>> 
>> What I don’t like about [NSArray.self] is that it’s an artefact of bridging. 
>> I’m not actually using it in the encoder:
>> 
>> coder.encode(arrayOfInts, forKey: kArrayKey)
> 
> The declaration:
> 
> encode(_ object: Any?, forKey key: String)
> 
> seems to indicate that it encodes any object

Yeah, you’re right, it’s secure on the decoding side only. 

This “encode” method is @objc, as I think you already noted, which AFAIK means 
that if the value is an array, it’s going to be automatically bridged to a 
NSArray. I would also expect it to become NSArray<NSNumber*>*, but I can’t 
remember the rules, so I won’t go out on that limb. I also haven’t looked at 
secure decoding recently, so I don’t know why or if the absence of the element 
type matters when you’re securely decoding. It used to.

Note that the first parameter (“Any?”) doesn’t have to be an object in Swift, 
although an object reference is required for the Obj-C method underneath. If 
it’s a non-object in Swift, it’s actually passed as an opaque object that wraps 
the Swift value.

After a while, you start to feel you need a ouija board to figure this stuff 
out. As an alternative, if you are in control of both encoding and decoding, 
and don’t need Obj-C compatibility inside the archive, you might do better to 
use encode/decodeEncodable instead of encode/decodeObject. That takes type 
bridging out of the picture, and trill preserves Swift types.

The last piece of this is that you should use one of the “decodeTopLevel…” 
methods to decode the root object of your archive, for example 
“decodeTopLevelDecodable(_:forKey:)”. This enables the relatively new — only 5 
years old! — failable decoding mechanism, where an error is thrown at the top 
level if any of the decoding fails anywhere in the archive, distinguishing 
failure from an init?(coder:) method that merely returns nil to signify an 
optional value that isn’t present. (You use “failWithError” to supply an error 
if you need to fail the decoding.)

Putting all that together, you can use NSKeyedArchiver/Unarchiver to encode and 
decode more or less completely in the Swift domain (Codable), with proper error 
handling and no obscure messing around with the types.
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to