将Set <CustomObject>存储到UserDefaults

时间:2019-07-07 08:59:12

标签: ios arrays swift set userdefaults

我有一个自定义类,可用作Set<ListItem>。我想将其存储到userDefaults。但是,尝试时出现Attempt to set a non-property-list object as an NSUserDefaults错误。我试图将其更改为Array,然后保存它,但仍然是相同的错误。在看到一些帖子后,我还尝试了“另存为数据”,这再次给了我下面的错误。

  

NSForwarding:警告:类'iTunes_Search_Me.ListItem'的对象0x600003bf9a00没有实现methodSignatureForSelector:-遇到麻烦

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 个答案:

答案 0 :(得分:4)

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

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

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

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

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

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

答案 1 :(得分:0)

您可以尝试首先设置保存的数据:

struct saveData{
   static let encoded = "encoded"
}

然后将其保存在该键下:

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

或尝试将其另存为字符串。