0

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")

1 Answer 1

3

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) }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.