1

I am not sure if this is an early swift bug or if I am doing something wrong. I have my custom class object that I want to save on the user defaults. For that I need to encode NSData of my custom object:

var myEncodedObject:NSData = NSKeyedArchiver.archivedDataWithRootObject(myObject)

The thing is that I am getting an error and I think this could be a bug.

2014-07-05 15:25:35.317 myAppName[12323:1008333] -[_myAppName encodeWithCoder:]: unrecognized selector sent to instance 0x1190c7f0
2014-07-05 15:25:35.323 myAppName[12323:1008333] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_myAppName encodeWithCoder:]: unrecognized selector sent to instance 0x1190c7f0'

Anyone having the same problem or know how to bypass this?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Andre Cytryn
  • 2,506
  • 4
  • 28
  • 43

1 Answers1

1

NSKeyedArchiver is calling encodeWithCoder: on your object, which apparently doesn't implement it.

Basically, you need to tell the archiver how to encode your object. The way this is done in Cocoa is having your class to implement the NSCoding protocol, which defined two methods:

  • encodeWithCoder:
  • initWithCoder:

Check How to use NSCoder for more information about how to conform. It's an Objective-C question, but the conversion to swift should be straightforward.

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235