0

I've used below struct as a variable (and filled it with json info), but i get an erro when trying to save it to userdefaults, the error says: "Attempt to insert non-property list object".

I've read some other threads but am not exactly sure what the problem is, would appreciate it if anyone could point me in the right direction.

// MARK: - Main
struct Main: Codable {
    var meta = Meta()
    var objects = [Object]()
}

// MARK: - Meta
struct Meta: Codable {
    var status = ""
    var count = 0
    var offset = 0
    var totalcount = 0
}

// MARK: - Object
struct Object: Codable {
    let id: Int
    let url: String
    let displayname: String
    let inventory: [Inventory]
    let media: [Media]
}


// MARK: - Inventory
struct Inventory: Codable {
   let id, warehouseid, instock, threshold: Int
    let reserved: Int
    let coordinates, note: String
    let prodno: Int
    let lastinventory: String
    let soldout, onpurchaseorders, generation: Int
    let created, changed: String
}

// MARK: - Media
struct Media: Codable {
    let id, prodno: Int
    let webpath: String
    let slot: Int
    let type, extdata: String
    let ctime, xsize, ysize, mediasetid: Int
    let alt, title: String
    let generation: Int
    let created, changed: String
}

This is how I'm trying to use it (only showing the used code):

class {

let userdefaults = UserDefaults()


Viewdidload
{
if let value = userdefaults.value(forKey: "data") as? Main
       {
        sökresultat = value
       }
}


self.userdefaults.setValue(self.sökresultat, forKey: "data")

}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Axxi
  • 193
  • 1
  • 10
  • 1
    You need to encode into Data the value before saving them. https://www.hackingwithswift.com/example-code/system/how-to-load-and-save-a-struct-in-userdefaults-using-codable See the doc: `A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.` of UserDefaults. https://stackoverflow.com/questions/44876420/save-struct-to-userdefaults etc. – Larme Feb 02 '21 at 14:40
  • @Larme Thank you, i'll look into this asap. – Axxi Feb 02 '21 at 14:45

0 Answers0