ios - 无法使用 NSCoding 归档嵌套自定义对象

标签 ios swift nscoding archiving

我有以下数据架构,其中Orchestra有许多Section,每个Section有许多Player >s:

enter image description here

所有 3 个类都符合 NSCoding 协议(protocol)并实现了必要的方法。 According to this SO question ,它应该可以工作,因为 NSCoding 是递归工作的。

Orchestra 单例类中,我有以下用于保存和检索 Section 的方法:

let sectionArchivalURL: URL = {

    let documentDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentDirectory = documentDirectories.first!

    return documentDirectory.appendingPathComponent("sections.archive") //gets archived Player objects
} ()

func saveChanges() -> Bool {
    print ("Saving sections to: \(sectionArchivalURL.path)")
    return NSKeyedArchiver.archiveRootObject(allSections, toFile: sectionArchivalURL.path)
}

Section 也符合 NSCoding:

//MARK: - NSCoding methods
func encode(with aCoder: NSCoder) {
    aCoder.encode(sectionName, forKey: "sectionName")
    aCoder.encode(allPlayers, forKey: "allPlayers")
}

required init(coder aDecoder: NSCoder) {

    sectionName = aDecoder.decodeObject(forKey: "sectionName") as! String
    allPlayers = aDecoder.decodeObject(forKey: "allPlayers") as! [Player]

    super.init()
}

同样,Player也符合NSCoding:

//MARK: - NSCoding methods
func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey: "playerName")        
    print ("encoding Player") //does not get called
}

required init(coder aDecoder: NSCoder) {

    name = aDecoder.decodeObject(forKey: "playerName") as! String
    super.init()
}

保存已确认有效。但是,当应用程序重新启动时,我可以查看我的团队,但包含的 Player。我还知道 Player 中的编码函数没有被调用。我做错了什么?

最佳答案

除了你的 Player 类之外,一切保持不变。这是我让它工作的方法:

    func encode(with aCoder: NSCoder) {
        let encName = NSKeyedArchiver.archivedData(withRootObject: name)
        aCoder.encode(encName, forKey: "playerName")        
        print ("encoding Player")
    }

    required init(coder aDecoder: NSCoder) {
        let tmpName = aDecoder.decodeObject(forKey: "playerName")
        name = NSKeyedUnarchiver.unarchiveObject(with: tmpName as! Data) as! String
    }

关于ios - 无法使用 NSCoding 归档嵌套自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43191894/

相关文章:

iphone - 如果不在 iphone 应用程序中向下滚动,Scrollview 不会显示其内容的顶部

swift - 如何在不影响其 subview 及其自身文本的情况下设置 View 的 Alpha?

iphone - 从 NSCoder 解码对象时,最好的中止方法是什么?

ios - 圆圈内数字的 CSS,iOS 的位置已关闭

ios - Popover 适配内容大小 IOS

ios:提前 3 周(按日期)

xcode - Swift 2.0 : Could not find overload. 需要解释

objective-c - 使用 NSData 和 NSCoding 加载 iOS 自定义文件格式

ios - 我需要一些帮助来归档 NSArray 以保存一些值并稍后添加/删除它们

ios - ios进度条不显示