My Object符合新的Swift 4 Codeable
协议。如何在UserDefaults
?
struct MyObject: Codeable {
var name: String
var something: [String]
}
myObjectsArray = [MyObject]() // filled with objects
UserDefaults.standard.set(myObjectsArray, forKey: "user_filters")
错误
由于未捕获的异常而终止应用 ' NSInvalidArgumentException',原因:'尝试插入非属性 列表对象
答案 0 :(得分:10)
哇,我开始工作了:
以下是使用Array
对象保存Codeable
的 Swift 4 语法:
我的解决方案是将其编码为JSON对象并保存:
static var getAllObjects: [MyObject] {
let defaultObject = MyObject(name: "My Object Name")
if let objects = UserDefaults.standard.value(forKey: "user_objects") as? Data {
let decoder = JSONDecoder()
if let objectsDecoded = try? decoder.decode(Array.self, from: objects) as [MyObject] {
return objectsDecoded
} else {
return [defaultObject]
}
} else {
return [defaultObject]
}
}
static func saveAllObjects(allObjects: [MyObject]) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(allObjects){
UserDefaults.standard.set(encoded, forKey: "user_objects")
}
}