Unrecognized selector sent to instance while archiving data (NSCoding)

SteBra picture SteBra · Mar 4, 2014 · Viewed 25.2k times · Source
-(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.

Answer

Grzegorz Krukowski picture Grzegorz Krukowski · Mar 4, 2014

You need to implement NSCoding protocol inside your Furniture object:

- (void)encodeWithCoder:(NSCoder *)aCoder{
  [aCoder encodeObject:self.yourpoperty forKey:@"PROPERTY_KEY"];
}

-(id)initWithCoder:(NSCoder *)aDecoder{
  if(self = [super init]){
    self.yourpoperty = [aDecoder decodeObjectForKey:@"PROPERTY_KEY"];
  }
  return self;
}

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.