Tags
swift
Asked 4 years ago
13 Jan 2020
Views 2121
iptracker

iptracker posted

[User Defaults] Attempt to set a non-property-list object

[User Defaults] Attempt to set a non-property-list object as an NSUserDefaults/CFPreferences value for key "keyname"

i have object array and i want to store it in UserDefaults
but

                                        UserDefaults.standard.set(myLoactionlist, forKey: "locationlist")


it not storing and it giving error as above
rajiv

rajiv
answered Apr 25 '23 00:00

The error "Attempt to set a non-property-list object" can occur when you're trying to save an object to UserDefaults that doesn't conform to the property-list format. The property-list format supports objects like arrays, dictionaries, strings, numbers, dates, and data. If you try to save an object that doesn't fit this format, you'll get the "Attempt to set a non-property-list object" error.

Let's take an example in Swift where we're trying to save an instance of a custom object called MyCustomObject to UserDefaults:



lass MyCustomObject {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}


let myObject = MyCustomObject(name: "John", age: 30)
UserDefaults.standard.set(myObject, forKey: "myObjectKey")

In this code, we're trying to save myObject to UserDefaults, but since MyCustomObject is not a property-list object, we'll get the "Attempt to set a non-property-list object" error.

To solve this, we need to either convert MyCustomObject to a property-list object or use a different approach to store the custom object. One way to convert MyCustomObject to a property-list object is to make it conform to the Codable protocol and encode it to JSON before saving it to UserDefaults:


class MyCustomObject: Codable {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let myObject = MyCustomObject(name: "John", age: 30)
let encoder = JSONEncoder()
if let encodedObject = try? encoder.encode(myObject) {
    UserDefaults.standard.set(encodedObject, forKey: "myObjectKey")
}

In this code, we've made MyCustomObject conform to Codable and used JSONEncoder to encode it to JSON. We then saved the encoded object to UserDefaults. To retrieve the object, we can decode it using JSONDecoder :



if let encodedObject = UserDefaults.standard.data(forKey: "myObjectKey") {
    let decoder = JSONDecoder()
    if let decodedObject = try? decoder.decode(MyCustomObject.self, from: encodedObject) {
        print(decodedObject.name) // prints "John"
        print(decodedObject.age) // prints 30
    }
} 

In this code, we've retrieved the encoded object from UserDefaults, created a JSONDecoder instance, and used it to decode the object back to MyCustomObject . We can then access the object's properties as usual.
Post Answer