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

时间:2017-04-03 18:32:24

标签: ios swift nscoding archiving

我有以下数据架构,其中Orchestra有很多Section个,而SectionPlayer有很多{<1}}:

enter image description here

所有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中的编码函数没有被调用。我做错了什么?

1 个答案:

答案 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
    }