简体   繁体   中英

Trying to save an array of objects into UserDefaults

im trying to save an array of objects into userdafaults and I got error "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")

In Swift the most reasonable way is to adopt Codable and save the array either as Property List or 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) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM