使用嵌套自定义对象进行NSCoding? [英] NSCoding with Nested Custom Objects?

查看:229
本文介绍了使用嵌套自定义对象进行NSCoding?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列嵌套对象,我需要通过NSCoding协议,以便我可以将顶级对象保存到NSUserDefaults。

I have a series of nested objects that I am needing to put through the NSCoding protocol so that I can save the top level object into NSUserDefaults.

以下是对象的结构:

'讲师'班级


  • NSMutableArray,包含...的实例。

'Class'class

'Class' class


  • NSMutableArray,包含...的实例

'学生'班级


  • 姓名属性

  • 编号属性

  • Money Property

我需要将一个Instructor实例保存到NSUserDefaults或该应用程序的文档。正如您所看到的,Instructor对象持有一个数组,然后该数组将保存一个类的实例。该类对象持有学生的实例。

I am needing to save an instance of Instructor to NSUserDefaults or to documents for the app. As you can see the Instructor object is holding an array that is then holding instances of a class. That class object is holding instances of students.

NSCoding协议是递归的吗?我的意思是,如果我将NSCoding协议添加到每个类,我可以保存一个Instructor对象,它会递归编码包含的对象?

Is the NSCoding protocol recursive? What I mean by that is if I add the NSCoding protocol to each class, I could then save an Instructor object and it would recursively encode the contained objects?

解码时它会以相同的方式工作吗?我可以解码一个教师类,它会递归解码所包含的对象,因为它们也符合NSCoding协议?

Would it then work the same way while decoding? I could just decode the one instructor class and it would recursively decode the objects contained because they also conform to the NSCoding protocol?

我怎样才能设置它?

推荐答案

是的,您可以(并且可能应该)编写您对NSCoding的支持以进行递归。这就是NSCoding应该如何工作的。

Yes, you can (and probably should) write your support for NSCoding to be recursive. That's how NSCoding is supposed to work.

当您的工具编码为fedWithCoder时,只需调用

When your implement encodeWithCoder, simply call

[coder encodeObject: aProperty forKey: @"propertyName"];

,包括它的容器属性。

然后确保对象的对象图中的每个对象也符合NSCoding。

Then make sure every object in your object's object graph also conforms to NSCoding.

对于标量属性,可以使用NS编码方法保存标量值,如encodeInt :forKey:

For scalar properties, you can save the scalar value using NSCoder methods like encodeInt:forKey:

要将符合NSCoding的对象保存为用户默认值,请先使用NSKeyedArchiver类方法archivedDataWithRootObject将其转换为NSData,然后将结果数据保存为默认值。很简单,真的。

To save an object that conforms to NSCoding to user defaults, first convert it to NSData using the NSKeyedArchiver class method archivedDataWithRootObject, then save the resulting data into defaults. Quite simple, really.

这篇关于使用嵌套自定义对象进行NSCoding?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆