问题
I have a dictionary (it's mutable if that makes a difference) which contains nsarrays, which in turn contain (subclass of NSObject)s I have implemented initWithCoder and encodeWithCoder like this:
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
self.Title = [aDecoder decodeObjectForKey:@"Title"];
self.SiteAPIURL = [aDecoder decodeObjectForKey:@"SiteAPIURL"];
self.ID = [aDecoder decodeObjectForKey:@"ID"];
return self;
}
-(void) encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.Title forKey:@"Title"];
[aCoder encodeObject:self.SiteAPIURL forKey:@"SiteAPIURL"];
[aCoder encodeObject:self.ID forKey:@"ID"];
}
But it doesn't save properly when I do [dictionary writeToFile:savepath atomically:YES];
So what am I doing wrong, and what exactly is serialization and do I need I need to use NSKeyedArchiver or something?
回答1:
[NSDictionary writeToFile: atomically:] uses NSPropertyListSerialization, which can only record a subset of primitive objects (numbers, strings, dates and data). So while you could use NSCoding along with NSKeyedArchiver to archive the objects, another option is to marshal your objects into a string or data representation, store that in the property list, and unmarshal them again on loading.
回答2:
Yes, you want to use a NSKeyedArchiver
All the info you need can be found here:
http://developer.apple.com/library/ios/ipad/#documentation/Cocoa/Conceptual/Archiving/Archiving.html
来源:https://stackoverflow.com/questions/4235485/saving-an-nsdictionary-of-nsarrays-of-custom-objects