Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode NSArray or NSDictionary using NSCoder

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!

like image 414
Ron Dear Avatar asked Feb 09 '10 02:02

Ron Dear


3 Answers

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];
like image 147
Cory Kilger Avatar answered Oct 06 '22 02:10

Cory Kilger


What kind of objects are you storing in the array? Make sure that all objects stored in the array implement the NSCoding protocol.

like image 36
Ole Begemann Avatar answered Oct 06 '22 03:10

Ole Begemann


NSKeyedArchiver/Unarchiver should encode and decode NSArrays and NSDictionaries with no problem. If your packet class you've created implements the NSCoding protocol, you need to explicitly call [encodeObject:myNsArrayforKey:@"stringsArray"] in your -encodeWithCoder: method (assuming that myNsArray is the name of the instance variable in your packet object you want to encode). But then the archiver and NSArray should take care of the rest of it. If you're doing this, it would be helpful to hear more about the layout of your classes and who's calling who when encoding/decoding.

like image 32
Ben Zotto Avatar answered Oct 06 '22 04:10

Ben Zotto