我有以下数据架构,其中Orchestra
有很多Section
个,而Section
个Player
有很多{<1}}:
所有3个类符合NSCoding
协议并且已实施必要的方法。 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
中的编码函数没有被调用。我做错了什么?
答案 0 :(得分:0)
除了您的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
}