Search code examples
iosarraysswiftsetuserdefaults

Storing Set<CustomObject> to UserDefaults


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


Solution

  • 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)
          }
      }