首页 > 解决方案 > 类与键的键值编码不兼容;变量作为一个集合

问题描述

我一直在尝试使用基于反射的键值编码来保持我的代码灵活和动态,但是我在尝试检索和设置某些属性时遇到了意外问题。

发生的错误是“此类不符合键 [众多键之一] 的键值编码”。相关性类别如下:

class Vote: NSObject & Codable {
    
    var id: String
    var userIdentifier: String
    var dateTimes: Set<Date>?
    var candidates: Set<String>?
    var filters: Set<String>?
    var locations: Set<String>?
    var moods: Set<String>?
    var prices: Set<Int>?
    var restrictions: Set<String>?

    enum CodingKeys: String, CodingKey {
        case id = "voteId"
        case userIdentifier = "userIdentifier"
        case candidates = "candidates"
        case dateTimes = "dateTimes"
        case filters = "filters"
        case locations = "locations"
        case moods = "moods"
        case prices = "prices"
        case restrictions = "restrictions"
    }
...

产生错误的行是:

someVoteInstance.value(forKey: "restrictions")

使用 value 和 setValue 的正确方法是什么,这样我可以让我的类既可编码又对 NSObject 函数友好?

标签: swiftobjective-cnsobjectnskeyvaluecoding

解决方案


推荐阅读