My custom objects conform to the NSCoding protocol with the following methods
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 app is crashing with the error SwiftValue encodeWithCoder - unrecognized selector sent to instance
Clearly this method is not available, so why is it not recognized?
Reference at https://developer.apple.com/reference/foundation/nscoding
Here is the archiver 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)
}
}
The problem is that you are trying to archive an optional. Replace this line:
if (object != nil) {
with:
if let object = object {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With