UserDefaults Custom Object of Custom Objects

后端 未结 1 1839
遇见更好的自我
遇见更好的自我 2021-01-24 20:05

Part of my settings I want to save with UserDefaults.

I already found this solution here: Save custom objects into NSUserDefaults

But I could not figure out how

1条回答
  •  广开言路
    2021-01-24 20:41

    Add given code in your class ConfigLabelMainList

    required convenience init?(coder aDecoder: NSCoder) {
    
        let midFirst = aDecoder.decodeObject(forKey: "midFirst") as! StatsIntervalModel
        let midSecond = aDecoder.decodeObject(forKey: "midSecond") as! StatsIntervalModel
        let midThird = aDecoder.decodeObject(forKey: "midThird") as! StatsIntervalModel
        let rightFirst = aDecoder.decodeObject(forKey: "rightFirst") as! StatsIntervalModel
        let rightSecond = aDecoder.decodeObject(forKey: "rightSecond") as! StatsIntervalModel
    
        self.init(labelMiddleFirst: midFirst, labelMiddleSecond: midSecond, labelMiddleThird: midThird, labelRightFirst: rightFirst, labelRightSecond: rightSecond)
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(labelMiddleFirst, forKey: "midFirst")
        aCoder.encode(labelMiddleSecond, forKey: "midSecond")
        aCoder.encode(labelMiddleThird, forKey: "midThird")
        aCoder.encode(labelRightFirst, forKey: "rightFirst")
        aCoder.encode(labelRightSecond, forKey: "rightSecond")
    }
    

    Now simply archive data and save it in defaults.

    0 讨论(0)
提交回复
热议问题