如何将带有对象的数组保存到UserDefaults

时间:2017-07-12 12:44:01

标签: swift4 userdefaults

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',原因:'尝试插入非属性   列表对象

1 个答案:

答案 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")
      }
 }