-(void)transformObjects:(NSMutableArray*)array key:(NSString*)key
{
NSMutableArray* archiveArray = [[NSMutableArray alloc]initWithCapacity:array.count];
for (Furniture *furniture in array) {
// The error occurs on the line below
NSData *furnitureEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:furniture];
[archiveArray addObject:furnitureEncodedObject];
}
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:archiveArray forKey:key];
}
Error log:
2014-03-04 10:55:27.881 AppName[10641:60b] -[Furniture encodeWithCoder:]: unrecognized selector sent to instance 0x15d43350
I have no idea why do I get "unrecognized selector sent to instance" when trying to archive an object.
You need to implement NSCoding protocol inside your Furniture object:
Basically you specify what should be written (encoded) and read from a file (decoded). Usually for each property you want to store in a file, you make same as I did here in an example.
You have a custom class
Furniture
which you are trying to archive withNSKeyedArchiver
. In order for this to work, theFurniture
class needs to conform to the< NSCoding >
protocol. Which means implementing theencodeWithCoder:
andinitWithCoder:
methods.Currently you don't implement these methods. You need to add them.
I think your Furniture class does not implement the NSCoding protocol.
For Swift 4.1 (tested code)
Note : NSCoding protocol is important
You'll need to implement
NSCoding
- here is an example with an object calledSNStock
that has two string properties,ticker
andname
: