使用NSUserDefaults Swift使类实例可以保存

时间:2016-06-16 12:00:38

标签: ios swift macos

我是编程iOS-Apps和Swift的新手。我尝试将自定义类的类实例保存到NSUserDefaults,但是当我尝试从存储中恢复保存的数据时,我会收到nil。 我找不到我的错误,我不知道它可以隐藏在哪里,所以我将在下面发布所有相关的代码块。谢谢你的帮助! :)

这是我的代码:

class Note: NSObject, NSCoding{

    var note: Int?
    var position: Int?
    var fach: String?
    var fachtyp: String?

    required init(coder aDecoder: NSCoder) {
        self.note = aDecoder.decodeObjectForKey("note") as? Int
        self.position = aDecoder.decodeObjectForKey("position") as? Int
        self.fach = aDecoder.decodeObjectForKey("fach") as? String
        self.fachtyp = aDecoder.decodeObjectForKey("fachtyp") as? String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.note, forKey: "note")
        aCoder.encodeObject(self.position, forKey: "position")
        aCoder.encodeObject(self.fach, forKey: "fach")
        aCoder.encodeObject(self.fachtyp, forKey: "fachtyp")
    }
}
class Fach: NSObject, NSCoding{
    var fachNoten: [Note] = []
    init(fachNoten: [Note]){
        self.fachNoten = fachNoten
        super.init()
    }


    required init(coder aDecoder: NSCoder) {
        self.fachNoten = (aDecoder.decodeObjectForKey("fachNoten") as? [Note])!
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.fachNoten, forKey: "fachNoten")
    }

}
var hallo1 = [Fach(fachNoten: [])]
var hallo2 = [Fach(fachNoten: [])]
var gesamtarray: [String: [Fach]] = ["Hallo1": hallo1, "Hallo2": hallo2]
var testarray: [String: [Fach]] = [:]

func save() {
    let savedData = NSKeyedArchiver.archivedDataWithRootObject(gesamtarray)
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(savedData, forKey: "gesamtarray")
    _ = defaults.synchronize()
}

func restore() {
    let defaults = NSUserDefaults.standardUserDefaults()
    if let savedData = defaults.objectForKey("gesamtarray") as? NSData {
        testarray = NSKeyedUnarchiver.unarchiveObjectWithData(savedData) as! [String: [Fach]]
    }
    else {
        print("Couldn't save")
    }
}

0 个答案:

没有答案