I am using NSSecureCoding to encode/decode some objects and in the process of testing multiple ways to unarchive an object noticed that removing some print statements changed the decoder behavior. Does the NSCoder object get "trashed" when an object is removed? Is this expected behavior?
Before
For example, This FakeObject is stored under the "FakeObjectKey". If I attempt to decode it 3 different ways and print the output it will be as follows.
print("FakeObject exists? \(coder.containsValue(forKey: "FakeObjectKey"))")
print("FakeObject insecure? \(coder.decodeObject(forKey: "FakeObjectKey"))")
print("FakeObject secure? \(coder.decodeObject(of: FakeObject.self, forKey: "FakeObjectKey"))")
Output where it appears to work and then fail twice:
FakeStorekeeper exists? true
FakeStorekeeper insecure? nil
FakeStorekeeper secure? nil
After
But if I comment out the first two print statements you can see the third method actually succeeds:
// print("FakeObject exists? \(coder.containsValue(forKey: "FakeObjectKey"))")
// print("FakeObject insecure? \(coder.decodeObject(forKey: "FakeObjectKey"))")
print("FakeObject secure? \(coder.decodeObject(of: FakeObject.self, forKey: "FakeObjectKey"))")
The output changes:
FakeObject secure? Optional(< FakeObject: 0x60000022a180>)
Apparently,
NSCodergets trashed when you decode an object from it and subsequent calls to decode the same object/key will silently fail. As far as I can tell this is undefined behavior. Be careful out there.