是否可以将自定义对象序列化到 Objective-C 中的 plist 文件?
为了简单起见,我们假设我们有以下简单的类接口:
@interface Person : NSObject <NSCoding> {
NSString *firstname;
NSString *lastname;
}
@property (copy) NSString *firstname;
@property (copy) NSString *lastname;
@end
是否可以将此对象序列化为 plist(假设 NSCoding 协议已正确实现)?
更新2010年12月31日14:40
我对此有一些后续问题。是否可以让 NSKeyedArchiver 将 plist 导出为 XML?此外,是否可以将 XML 转储到变量而不是文件中?
For the sake of simplicity, let's assume that we have the following simple class interface:
@interface Person : NSObject <NSCoding> {
NSString *firstname;
NSString *lastname;
}
@property (copy) NSString *firstname;
@property (copy) NSString *lastname;
@end
Is it possible to serialize this object into a plist (assuming that the NSCoding protocol is implemented correctly)?
Update December, 31st 2010 14:40
I have some follow up questions on this. Is it possible to have NSKeyedArchiver
export the plist as XML? Furthermore, is it possible to dump the XML into variable instead of a file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当你给它一个 filename.plist 文件路径时,NSKeyedArchiver 会自动将对象保存到 plist 中。
NSKeyedArchiver will automatically save the object to a plist when you give it a filename.plist file path.
这似乎是 iOS 中的一个缺陷。我想知道它是否特定于用户默认 plist 的处理。
作为一种可能的解决方法,也许您可以尝试为您的设置管理 NSMutableDictionary 并直接将字典读/写为 plist 文件。
写入数据:
然后读回数据:
This appears to be a defect in iOS. I am wondering if it is specific to the handling of the user defaults plist though.
As a possible workaround, perhaps you could try managing an NSMutableDictionary for your settings and read/write the dictionary as a plist file directly.
To write the data:
Then to read the data back:
试试这个魔法:
要恢复它只需使用:
Try this magic:
To get it back out just use:
至于将输出格式设置为 XML,我建议:
至于将其放入变量而不是文件中,我建议使用 initForWritingWithMutableData: 初始值设定项创建 NSKeyedArchiver。编码完成后,
确保对其调用 finishEncoding,然后 XML 将位于您在初始化时传入的 NSMutableData 中。
如果您需要从中获取 NSString,您可以从 NSMutableData 获取它,如下所示:
这应该可以解决问题。祝你好运!
As for setting the output format to XML, I suggest:
As for getting it into a variable and not a file, I would suggest creating your NSKeyedArchiver with the initForWritingWithMutableData: initializer. Once finished encoding,
make sure to call finishEncoding on it, and then the XML will be in the NSMutableData that you passed in at init time.
If you then need to get an NSString from that, you can get that from your NSMutableData like so:
That should do the trick. Good luck!
是的。但是,它并不是很方便,因为您必须先对对象进行编码,然后将 NSData 对象保存到要保存到 plist 中的数组/字典中。
Yes, it is. However, its not really convenient as you have to encode the object first and then save the
NSData
object into the array/dictionary which you want to save into the plist.