保存自定义对象的 NSArray 的 NSDictionary
我有一个字典(如果有影响的话它是可变的),它包含 nsarrays,它又包含( NSObject 的子类) 我已经实现了 initWithCoder 和encodeWithCoder,如下所示:
-(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"];
}
但是当我执行 [dictionary writeToFile:savepathatomically:YES]; 时,它无法正确保存 那么我做错了什么,序列化到底是什么?我需要使用 NSKeyedArchiver 还是其他东西?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[NSDictionary writeToFile:atomically:]
使用NSPropertyListSerialization
,它只能记录原始对象的子集(数字、字符串、日期和数据)。因此,虽然您可以使用NSCoding
和NSKeyedArchiver
来归档对象,但另一种选择是将对象编组为字符串或数据表示形式,存储 在属性列表中,并在加载时再次解组它们。[NSDictionary writeToFile: atomically:]
usesNSPropertyListSerialization
, which can only record a subset of primitive objects (numbers, strings, dates and data). So while you could useNSCoding
along withNSKeyedArchiver
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.是的,您想使用 NSKeyedArchiver
您需要的所有信息都可以在这里找到:
http://developer.apple.com/library/ios/ipad/#documentation/Cocoa/Conceptual/Archiving/Archiving.html
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