本文介绍了存储Set< CustomObject>设为UserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类,可用作 Set< ListItem> .我想将其存储到userDefaults.但是,我尝试尝试将非属性列表对象设置为NSUserDefaults 错误.我试图将其更改为 Array ,然后将其保存,但仍然是相同的错误.在看到一些帖子后,我还尝试了另存为数据",这再次给了我下面的错误.

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.

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

尝试设置非属性-list对象作为NSUserDefaults

推荐答案

您可以将模型设置为 UserDefaults ,如下所示:

You can set the model to UserDefaults like this:

  • 首先,您应该创建模型的实例

  • Firstly you should create an instance of your model

然后您可以将模型保存到 UserDefaults :

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

您可以像这样从 UserDefaults 获取模型

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

这篇关于存储Set&lt; CustomObject&gt;设为UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 10:20