user3840260
user3840260

Reputation:

NSCoding encode Array of Objects

I need to encode an array containing multiple instances of a custom NSObject class. However, upon doing so, it returns a crash with message :

-[Person encodeWithCoder:]: unrecognized selector sent to instance 0x8ff2c50

the class contains multiple properties and to store them as a collection is the purpose of the class.

the encoder method upon which it crashes is such:

- (void)encodeWithCoder:(NSCoder *)encoder 
{
    [encoder encodeObject:_arrayOfPeople forKey:@"DataStoragePeopleArray"];
}

Upvotes: 2

Views: 3203

Answers (2)

ChenSmile
ChenSmile

Reputation: 3441

I hope it will work.....

-(void)encodeWithCoder:(NSCoder *)aCoder
  {
   [aCoder encodeObject:_arrayOfPeople forKey:@"DataStoragePeopleArray"];
  }

-(id)initWithCoder:(NSCoder *)aCoder
{
   if(self = [super init]){
   self.yourpoperty = [aCoder decodeObjectforKey:@"DataStoragePeopleArray"];
  }
   return self;
  }

Upvotes: 0

JoeFryer
JoeFryer

Reputation: 2751

You need to implement the NSCoding protocol in your Person class. Any custom class you wish to encode, including when it is contained in a collection you are encoding, needs to implement NSCoding.

You'll need to implement encodeWithCoder: and initWithCoder:.

Here is the documentation for the NSCoding protocol:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html

Upvotes: 4

Related Questions