1
我對iOS開發一般比較陌生,但我正在編寫這個應用程序。Swift中的NSCoding無法正確存檔數據?
我有自定義對象「學期」,「課程」和「作業」。學期包含課程和課程陣列包含作業陣列。我可以正確歸檔學期和課程信息,但由於某些原因,分配信息無法讀取。
學期:
required init?(coder aDecoder: NSCoder) {
self.name = ""
super.init()
if let archivedName = aDecoder.decodeObject(forKey: "name") as? String {
name = archivedName
}
if let archivedCourses = aDecoder.decodeObject(forKey: "courses") as? [Course] {
courses = archivedCourses
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(courses, forKey: "courses")
}
課程:
required init?(coder aDecoder: NSCoder) {
self.name = ""
super.init()
if let archivedName = aDecoder.decodeObject(forKey: "courseName") as? String {
name = archivedName
}
if let archivedAssignments = aDecoder.decodeObject(forKey: "assignments") as? [Assignment] {
assignments = archivedAssignments
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "courseName")
aCoder.encode(assignments, forKey: "assignments")
分配:
required init?(coder aDecoder: NSCoder) {
self.name = ""
self.grade = 0
self.weight = 0
super.init()
if let archivedName = aDecoder.decodeObject(forKey: "assignmentName") as? String, let archivedGrade = aDecoder.decodeObject(forKey: "assignmentGrade") as? Int, let archivedWeight = aDecoder.decodeObject(forKey: "assignmentWeight") as? Int {
name = archivedName
grade = archivedGrade
weight = archivedWeight
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "assignmentName")
aCoder.encode(grade, forKey: "assignmentGrade")
aCoder.encode(weight, forKey: "assignmentWeight")
}
我不知道爲什麼,但是當我嘗試無法讀取的分配細節解碼對象。
decoderObject有特殊方法解碼Ints –
我的回答對你有幫助嗎?任何反饋意見,謝謝 –
是的,它確實!謝謝你的幫助!! –