UserDefaults 自定义对象的自定义对象
Posted
技术标签:
【中文标题】UserDefaults 自定义对象的自定义对象【英文标题】:UserDefaults Custom Object of Custom Objects 【发布时间】:2018-04-25 15:14:24 【问题描述】:我想用 UserDefaults 保存我的部分设置。
我已经在这里找到了这个解决方案: Save custom objects into NSUserDefaults
但如果自定义对象中有自定义对象,我不知道如何保存。
我的课程如下所示:
class ConfigLabelMainList: NSObject, NSCoding
var labelMiddleFirst: StatsIntervalModel
var labelMiddleSecond: StatsIntervalModel
var labelMiddleThird: StatsIntervalModel
var labelRightFirst: StatsIntervalModel
var labelRightSecond: StatsIntervalModel
init(labelMiddleFirst: StatsIntervalModel, labelMiddleSecond: StatsIntervalModel, labelMiddleThird: StatsIntervalModel, labelRightFirst: StatsIntervalModel, labelRightSecond: StatsIntervalModel)
self.labelMiddleFirst = labelMiddleFirst
self.labelMiddleSecond = labelMiddleSecond
self.labelMiddleThird = labelMiddleThird
self.labelRightFirst = labelRightFirst
self.labelRightSecond = labelRightSecond
func encode(with aCoder: NSCoder)
required convenience init?(coder aDecoder: NSCoder)
class StatsIntervalModel: NSObject, NSCoding
var stat: String
var interval: String
init(stat: String, interval: String)
self.stat = stat
self.interval = interval
required convenience init?(coder aDecoder: NSCoder)
let stat = aDecoder.decodeObject(forKey: "stat") as! String
let interval = aDecoder.decodeObject(forKey: "interval") as! String
self.init(stat: stat, interval: interval)
func encode(with aCoder: NSCoder)
aCoder.encode(stat, forKey: "stat")
aCoder.encode(interval, forKey: "interval")
解决方案是什么样的?
【问题讨论】:
没有区别。就像在StatsIntervalModel
中所做的一样,只需对 ConfigLabelMainList
的属性进行编码和解码。
【参考方案1】:
在你的类中添加给定的代码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")
现在只需归档数据并将其保存为默认值。
【讨论】:
谢谢,这有帮助!以上是关于UserDefaults 自定义对象的自定义对象的主要内容,如果未能解决你的问题,请参考以下文章
尝试使用 NSKeyedArchiver 在 UserDefaults 中保存自定义对象