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)
    }
}
MechEngineer
  • 1,399
  • 3
  • 16
  • 27
  • In my case, I was migrating app from swift 2 to 4, and the encoding / decoding was not implementing well . so I just followed https://stackoverflow.com/a/37983027/5561910 – Maor May 07 '18 at 07:14

1 Answers1

5

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

if (object != nil) {

with:

if let object = object {
ganzogo
  • 2,516
  • 24
  • 36
  • 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. – MechEngineer Oct 26 '16 at 17:07
  • 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 – Rajath Kornaya Jun 28 '18 at 06:43
  • if self.eventDataArr.count > 0 { } this condition worked for me thanks – Rajath Kornaya Jun 28 '18 at 06:46