5

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)
    }
}
1
  • In my case, I was migrating app from swift 2 to 4, and the encoding / decoding was not implementing well . so I just followed stackoverflow.com/a/37983027/5561910 Commented May 7, 2018 at 7:14

1 Answer 1

5

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

if (object != nil) {

with:

if let object = object {
Sign up to request clarification or add additional context in comments.

3 Comments

Wow thank you for the clarification. That seems to have fixed it. I suppose nil comparison would work but I'd have to mark it non optional.
if let self.eventDataArr.count = self.eventDataArr.count in my case object is an array , I am getting below error Variable binding in a condition requires an initializer
if self.eventDataArr.count > 0 { } this condition worked for me thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.