1

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 ?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 ?
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.