尝试将对象数组保存到 UserDefaults
Trying to save an array of objects into UserDefaults
我正在尝试将对象数组保存到 userdafaults 中,但出现错误 "Attempt to set a non-property-list object"
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")
在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) }
我正在尝试将对象数组保存到 userdafaults 中,但出现错误 "Attempt to set a non-property-list object"
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")
在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) }