将包含另一个自定义对象的自定义对象保存到 NSUserDefaults 中
我了解如何在 NSUser Defaults 中存储自定义对象,但是当我尝试实现保存其中包含不同类型对象的对象时(如果我没有记错的话,它称为组合),请遵循与我相同的内部对象步骤对于第一个,我遇到了运行时错误。您能否详细描述一下我必须采取的步骤才能正确保存和检索所有内容
I understand how to store a custom object in NSUser Defaults but when i tried to implement saving an object with an object of different type inside it (it is called composition if i'm not mistaken) following the same steps for inner object as i did for the first one i got runtime error. Could you please minutely describe steps that i have to undertake in order to save and retrieve everything correctly
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的所有对象都应该实现 NSCoding 协议。 NSCoding 对要保存的对象递归地工作。例如,您有 2 个自定义类
要将 MyClass 对象保存到 NSUserDefaults,您需要对这两个类实现 NSCoding 协议:
对于第一个类:
对于第二个类:
注意,如果您的另一个类(上面的 MyAnotherClass)也有自定义对象 那么自定义对象也应该实现 NSCoding。即使你有隐式包含自定义对象的 NSArray,你也应该为这些对象实现 NSCoding。
All your objects should implement NSCoding protocol. NSCoding works recursively for objects that would be saved. For example, you have 2 custom classes
For saving MyClass object to NSUserDefaults you need to implement NSCoding protocol to both these classes:
For first class:
For second class:
Note, if your another class (MyAnotherClass above) has also custom object then that custom object should implement NSCoding as well. Even you have NSArray which implicity contains custom objects you should implement NSCoding for these objects.