My custom objects conform to the NSCoding protocol in the following ways
required init(coder decoder: NSCoder) {
super.init()
createdDate = decoder.decodeObject(forKey: "created_date") as? Date
userId = decoder.decodeInteger(forKey: "user_id")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(createdDate, forKey: "created_date")
aCoder.encode(userId, forKey: "user_id")
}
This is the correct method name for the nscoding protocol in Swift 3, however the application crashes with an error SwiftValue encodeWithCoder - unrecognized selector sent to instance
Obviously this method is not available, so why is it not recognized?
Link to https://developer.apple.com/reference/foundation/nscoding
Here is the archiving method I made
func encodeObject(_ defaults:UserDefaults, object:NSCoding?, key:String) {
if (object != nil) {
let encodedObject = NSKeyedArchiver.archivedData(withRootObject: object)
defaults.set(encodedObject, forKey: key)
} else {
defaults.removeObject(forKey: key)
}
}
source
share