如何保存我的結構與NSCoding,以便它不會改變,即使用戶 關閉應用程序?我將不勝感激,如果你也可以告訴我如何正確實施缺少的代碼。如何用NSCoding保存結構
更新與以下兩個新的功能: 這裏是我的代碼:
struct RandomItems: Codable
{
var items : [String]
var seen = 0
init(items:[String], seen: Int)
{
self.items = items
self.seen = seen
}
init(_ items:[String])
{ self.init(items: items, seen: 0) }
mutating func next() -> String
{
let index = Int(arc4random_uniform(UInt32(items.count - seen)))
let item = items.remove(at:index)
items.append(item)
seen = (seen + 1) % items.count
return item
}
func toPropertyList() -> [String: Any] {
return [
"items": items,
"seen": seen
]
}
}
override func viewWillDisappear(_ animated: Bool) {
UserDefaults.standard.set(try? PropertyListEncoder().encode(quotes), forKey:"quote2")
}
override func viewDidAppear(_ animated: Bool) {
if let data = UserDefaults.standard.value(forKey:"quote2") as? Data {
let quote3 = try? PropertyListDecoder().decode(Array<RandomItems>.self, from: data)
}
}
}
extension QuotesViewController.RandomItems {
init?(propertyList: [String: Any]) {
return nil
}
}
我怎樣才能確保整個陣列在此範圍內?
你需要把它變成一個類。您還需要子類化NSObject並使其符合NSCoding –
可能的重複[使用Swift將類中的結構保存到NSUserDefaults中](https://stackoverflow.com/questions/25546716/save-struct-in-class-to- nsuserdefaults-using-swift) – TNguyen