views:

962

answers:

1

Hello,

My NSMutableArray instance contains instances of different types of objects that have common ancestor. I want to serialize the array, but NSKeyedArchiver class seems to archive arrays contain certain types of objects. Is there an easy way to to this with stock serialization classes ?

+2  A: 

I don't think NSKeyedArchiver is your problem, since it doesn't know about arrays or anything. Perhaps you need to implement the NSCoding protocol on each subclass?

Edit:

Not sure how you're using your NSKeyedArchiver, but this is how you should use it:

NSMutableData *data = [NSMutableData new];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:array forKey:@"array"];
[data writeToFile:filename attomically:YES];
[archiver release];
[data release];

And to read it in later:

NSData *data = [[NSData alloc] initWithContentsOfFile:filename];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
array = [[unarchiver objectForKey:@"array"] retain];
[unarchiver release];
[data release];

This assumes that array is some type of NSObject, including NSArray, NSSet, NSDictionary, etc, or any of their mutable equivalents.

Ed Marty
I have implemented NSCoding protocol, but the coder instance only have "encodeArrayOfObjCType:count:at" method, which requires explicitly passing the type of the elements. Am I missing something ?
M. Utku ALTINKAYA
Yes you are missing something, each class should only need to encode itself. The NSMutableArray already knows how to archive itself (it encodes a count, and then all of the contained objects). So all you need to do is implement initWithCoder: and encodeWithCoder: in each of the subclasses you use. You do not need to explicitly encode arrays, if you subclass has such instance variables, just encode using encodeObject:forKey:, it will work on any class implementing the NSCoder protocol, including NSMutableArray.
PeyloW
Thank you Ed and Peylow, I thought the I have to use the method I mentioned above to serialize arrays, did not notice they also implements NSCoder protocol.
M. Utku ALTINKAYA