2017-08-25 66 views
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") 
} 

我不知道爲什麼,但是當我嘗試無法讀取的分配細節解碼對象。

+0

decoderObject有特殊方法解碼Ints –

+0

我的回答對你有幫助嗎?任何反饋意見,謝謝 –

+0

是的,它確實!謝謝你的幫助!! –

回答

0

我平時喜歡這個

if decoder.containsValue(forKey: "teamNumber"){ 
    self.teamNumber = decoder.decodeInteger(forKey: "teamNumber") 
} 

翻譯成你的問題將是這樣的解碼Int,改變你的Assignment類的init?(coder aDecoder: NSCoder)方法

required init?(coder aDecoder: NSCoder) { 

    self.name = "" 
    self.grade = 0 
    self.weight = 0 
    super.init() 

    if let archivedName = aDecoder.decodeObject(forKey: "assignmentName") as? String{ 
     self.name = archivedName 
    } 

    if decoder.containsValue(forKey: "assignmentGrade"){ 
     self.grade = decoder.decodeInteger(forKey: "assignmentGrade") 
    } 

    if decoder.containsValue(forKey: "assignmentWeight"){ 
     self.weight = decoder.decodeInteger(forKey: "assignmentWeight") 
    } 

} 

希望這有助於