我有以下数据架构,其中Orchestra
有许多Section
,每个Section
有许多Player
>s:
所有 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/