ios - Objective-C 会序列化/恢复具有多个引用的对象会创建重复的对象吗?

标签 ios objective-c serialization reference save

我正在构建游戏并实现游戏保存功能。它是对 encodeWithCoder: 的一系列调用。我在尝试重新初始化以下数据结构时遇到问题:

  • X 对 Y 有 strong 引用
  • Y 对 Z 有 strong 引用
  • Z 对 X 有赋值引用

为了序列化,我调用了 encodeWithCoder:

  • X 序列化 Y
  • Y 序列化 Z

如何恢复 Z 对 X 的引用? 要求 Z 序列化/反序列化它对 X 的引用是否合法,或者这会创建重复对象或无限循环吗?

现在我正在尝试通过为 X 使用通用 ID 来解决这个问题,因此 Z 知道 X 的通用 ID,并且在反序列化过程中的某个时刻,Z 会通过 ID 从某个列表中拉出 X 并将其分配回去到它的 X 引用。 是否有更好/更简单的方法来恢复对 X 的引用?

最佳答案

只需对对象进行编码,它们在写出时是唯一的。来自 the docs :

An object graph is not necessarily a simple tree structure. Two objects can contain references to each other, for example, creating a cycle. If a coder follows every link and blindly encodes each object it encounters, this circular reference will generate an infinite loop in the coder. Also, a single object can be referenced by several other objects. The coder must be able to recognize and handle multiple and circular references so that it does not encode more than one copy of each object, but still regenerate all the references when decoding.

To solve this problem, NSCoder introduces the concept of a root object. The root object is the starting point of an object graph. To encode an object graph, you invoke the NSCoder method encodeRootObject:, passing in the first object to encode. Every object encoded within the context of this invocation is tracked. If the coder is asked to encode an object more than once, the coder encodes a reference to the first encoding instead of encoding the object again.

关于ios - Objective-C 会序列化/恢复具有多个引用的对象会创建重复的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21492537/

相关文章:

iphone - 如何最好地设置 UITableViewCell 或 UIButton 的动画以重复亮起红色

ios - UIToolBar 是透明的

ios - 来自 typography.com 的 H&FJ 字体在 iOS 上看起来很糟糕

ios - 在长 NSString 中添加新行/换行符/段落

ios - 需要在所有 UIAlertController 关闭后执行操作

c# - 在一个 Json 中创建多个表而不使用 JArray?

ios - 在 iOS 中导航文件夹引用

objective-c - 函数调用而不是 self 消息传递——什么时候使用什么?

c# - Json.NET 根据属性类型使属性成为必需的

serialization - XStream <-> 替代二进制格式(例如 Protocol Buffer )