0

If you decode a data type with the wrong NSCoding function, the app crashes. For example, this line will crash if DoubleKey actually represents a double and not an integer as expected by decodeInteger:

    let isReallyDouble = aDecoder.decodeInteger(forKey: DoubleKey)

How do you verify the data type before decoding? This is important if version 1 of the app encodes some value as an integer but version 5 must change that variable to a double.

This is for Swift 3, where decodeObject doesn't work for value types like integer and double: Swift 3 saving and retrieving custom object from userDefaults

Resulting in a crash, instead of returning nil, when the data type is mismatched seems like an awfully poor design choice.

Crashalot
  • 33,605
  • 61
  • 269
  • 439
  • 1
    Use `decodeObject` and check the type yourself: https://developer.apple.com/documentation/foundation/nscoder/1414478-decodeobject – Alexander Jun 11 '17 at 19:30
  • @Alexander `decodeObject` doesn't work for value types like integer in Swift 3: https://stackoverflow.com/questions/37980432/swift-3-saving-and-retrieving-custom-object-from-userdefaults – Crashalot Jun 11 '17 at 19:32
  • You shouldn't change the type associated with a key. If you need to make a change as you described then you should use a new key, perhaps,changing the old property to an optional or change it to a computed variable so that it accesses the new property – Paulw11 Jun 11 '17 at 21:29

1 Answers1

2

Apple had a talk called "Data You can Trust" at 2018's WWDC. One of the topics discussed it the decoding of NSCodeable objects. See the link below to access the talk. Highly recommended.

https://developer.apple.com/videos/play/wwdc2018/222/

ADG
  • 343
  • 1
  • 9