Mr. Charbonneau has the right idea. An NSCoder
abstracts the specific serialization of your object, and lets you worry only about what needs to be serialized/deserialized. In -encodeWithCoder:
, you might want to
NSAssert1([encoder allowsKeyedCoding],
@"%@ does not support sequential archiving.",
[self className]);
as not all coders support keyed archiving.
In -initWithCoder
, you should be sending -initWithCoder:
– not simply -init
– to super
prior to initializing your object:
self = [super initWithCoder:decoder];
if (!self) return nil;
// now use the coder to initialize your state
Alternatively, since your object is basically a property list already, you can add something like -[Person plistRepresentation]
:
- (NSDictionary *)plistRepresentation
{
return [NSDictionary dictionaryWithObjectsAndKeys:
[self firstName], @"firstName",
[self lastName], @"lastName",
[NSNumber numberWithInteger:[self age]], @"age", nil];
}
Then, to serialize an array of Person
s, you can yourself transform the persons into their plistRepresentation
and then use -[NSArray writeToURL:atomically:]
. (You can of course also employ the methods of NSProperyListSerialization
directly.)