Encode NSArray or NSDictionary using NSCoder

Ron Dear picture Ron Dear · Feb 9, 2010 · Viewed 29.3k times · Source

I was wondering whether or not it is possible to use the NSCoder method:

- (void)encodeObject:(id)objv forKey:(NSString *)key

to encode either an instance of NSArray or NSDictionary. If not how do you go about encoding them? I am trying to use NSKeyedArchived / NSKeyedUnarchiver to send data between phones using GameKit. I tried it and cannot seem to retrieve the string I stored in my array. The packet class I made comes through along with the packet type integer, but not the data in the array it seems.

Thanks in advance!

Answer

Cory Kilger picture Cory Kilger · Feb 9, 2010

If the array or dictionary is the root object you should do

NSData * encodedData = [NSKeyedArchiver archivedDataWithRootObject:someArray];

or

BOOL success = [NSKeyedArchiver archiveRootObject:someArray toFile:filePath];

If it is an instance variable of a custom class, in the -encodeWithCoder: method should do

[coder encodeObject:someArray forKey:@"someArray"];

and then in the -initWithCoder: method

someArray = [[coder decodeObjectForKey:@"someArray"] retain];