Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 Xcode 8 - SwiftValue encodeWithCoder - unrecognized selector sent to instance

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)
    }
}
like image 615
MechEngineer Avatar asked Oct 26 '16 15:10

MechEngineer


1 Answers

The problem is that you are trying to archive an optional. Replace this line:

if (object != nil) {

with:

if let object = object {
like image 154
ganzogo Avatar answered Oct 13 '22 13:10

ganzogo