我具有以下数据体系结构,其中Orchestra
具有许多Section
,每个Section
具有许多Player
:
这3个类均符合NSCoding
协议,并已实现了必要的方法。 According to this SO question,它应该起作用,因为NSCoding递归起作用。
在Orchestra
单例类中,我具有以下用于保存和检索Section
s的方法:
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
中的编码功能没有被调用。我做错了什么? 最佳答案
保留所有相同的内容(播放器类除外)。这是我的工作方式:
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/