gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:48:25 25 4
gpt4 key购买 nike

我正在构建游戏并实现游戏保存功能。它是对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com