I have the following data architecture, where Orchestra
has many Section
s, and each Section
has many Player
s :
All 3 classes conform to NSCoding
protocol and have the necessary methods implemented. According to this SO question, it should work since NSCoding works recursively.
Inside the Orchestra
singleton class, I have the following methods for saving and retrieving 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
also conforms to 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()
}
Similarly, Player
also conforms to 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()
}
Saving is confirmed working. However, when the app relaunches, I am able to view my teams, but the containing Player
s are empty. I also know that the encoding function in Player
did not get called. What am I doing incorrectly?