0
votes

I have a custom class which I use as Set<ListItem>. I want to store this to userDefaults. However, I'm getting Attempt to set a non-property-list object as an NSUserDefaults error when trying to. I tried to change it to Array and then save it but still same error. I also tried Saving as data after saw some posts, again this gives me below error.

NSForwarding: warning: object 0x600003bf9a00 of class 'iTunes_Search_Me.ListItem' does not implement methodSignatureForSelector: -- trouble ahead

class ListItem: Codable ,Equatable, Hashable {
    let wrapperType, kind: String?
    let artistID, collectionID, trackID: Int?
    let artistName, collectionName, trackName: String?
    let trackViewURL: String?
    let artworkUrl30, artworkUrl60, artworkUrl100: String?
    let releaseDate: String?
    let primaryGenreName: String?
    var isSelected: Bool = false
    enum CodingKeys: String, CodingKey {
        case wrapperType, kind
        case artistID
        case collectionID
        case trackID
        case artistName, collectionName, trackName
        case trackViewURL
        case artworkUrl30, artworkUrl60, artworkUrl100, releaseDate, primaryGenreName
    }

    static func ==(lhs: ListItem, rhs: ListItem) -> Bool {
        return lhs.trackID == rhs.trackID
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(trackID)
    }
}

Attempt to set a non-property-list object as an NSUserDefaults

2
Maybe use some kind of database to do this kind of stuff?Sweeper
It is a less efficient way to solve it. Ex. CoreData. So storing just an array will be a better option but I don't know how to solve this problem.Emre Önder
What I mean is UserDefaults is not meant for storing this kind of data. It's meant for things like user preferences.Sweeper

2 Answers

2
votes

You can set the model to UserDefaults like this:

  • Firstly you should create an instance of your model

  • And then you can save your model to UserDefaults:

    let encoder = JSONEncoder()
    if let encoded = try? encoder.encode(listItemInstance) {
        let defaults = UserDefaults.standard
        defaults.set(encoded, forKey: "ListItemObject")
    }
    

    You can get model from UserDefaults like this

    if let savedItem = defaults.object(forKey: "ListItemObject") as? Data {
        let decoder = JSONDecoder()
        if let loadedItem = try? decoder.decode(ListItem.self, from: savedItem) {
            print(loadedItem)
        }
    }
    
0
votes

You could try first setting up saved data:

struct saveData{
   static let encoded = "encoded"
}

Then save it under that key:

UserDefaults.standard.set(encoded as! Data, forKey: "encoded")

or try saving it as a string instead.