在 grandparent-parent-child 数据模型关系中适当使用 NSCoding

Using NSCoding appropriately in a grandparent-parent-child data model relationships

我有一个 grandparent、parent 和 child 模型关系(Orchestra class 模型 object,其中包含许多Sections,每个包含许多 Players)。也就是说,Orchestraobject有属性叫var allSections: [Section]Sectionobject有属性叫var allPlayers: [Player]

我的目标是使用 NSCoding 保存所有三个模型的数据。 我很困惑我是否应该遵守 NSCoding 对于 (A) 所有 3 classes, (B) 只有 child class,或者 (C) 除了 child class 之外的所有 classes?我感到困惑的一个原因是 [NSCoding 是递归的][1]。

到目前为止,我已经为 Player:

实现了标准的 NSCoding 协议方法
func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "playerName")
        aCoder.encode(id, forKey: "playerId")
        aCoder.encode(playerStatus, forKey: "playerStatus")
        aCoder.encode(playerPosition, forKey: "playerPosition")

    }

    required init(coder aDecoder: NSCoder) {

        name = aDecoder.decodeObject(forKey: "playerName") as! String
        id = aDecoder.decodeObject(forKey: "playerId") as! String
        playerStatus = aDecoder.decodeObject(forKey: "playerStatus") as! PlayerStatus
        playerPosition = aDecoder.decodeObject(forKey: "playerPosition") as! PlayerPosition

        super.init()

    }

Sectioninit 方法中,我将调用:

if let archivedItems = NSKeyedUnarchiver.unarchiveObject(withFile: itemArchivalURL.path) as? [Item] {
            allPlayers = archivedItems
        }

如果您希望存档 Orchestra.

的实例,则所有 3 个都必须符合 NSCoding

如果您只想归档一个 Section 实例,那么只有 SectionPlayer 必须符合 NSCoding.

这样想。无论您希望存档什么对象,其本身都必须符合 NSCoding。在 class 中需要 encode/decode 的任何内容也必须符合 NSCoding。对于最终需要 encoded/decoded.

的所有 classes,这需要始终保持正确。