Saving an NSDictionary of NSArrays of custom objects

故事扮演 提交于 2019-12-08 04:13:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!