尝试将对象数组保存到UserDefaults中

时间:2019-10-26 06:35:33

标签: arrays swift nsuserdefaults

im试图将一组对象保存到userdafaults中,但出现错误“试图设置非属性列表对象”

import UIKit

var defaults = UserDefaults()
class Item {
    var title: String = ""
    var done: Bool = false
}

var array = [Item]()


let newTitle = Item()
newTitle.title = "hey"
array.append(newTitle)
let newTitle2 = Item()
newTitle2.title = "hey"
array.append(newTitle2)
let newTitle3 = Item()
newTitle3.title = "hey"
array.append(newTitle3)
let newTitle4 = Item()
newTitle4.title = "hey"
array.append(newTitle4)


defaults.set(array, forKey: "arrays")

1 个答案:

答案 0 :(得分:3)

在Swift中,最合理的方法是采用Codable并将数组保存为属性列表或JSON

class Item : Codable {
    var title: String = ""
    var done: Bool = false
}

...

do {
   let data = try JSONEncoder().encode(array)
   // or let data = try PropertyListEncoder().encode(array)
   defaults.set(data, forKey: "arrays")
} catch { print(error) }