在Swift(iOS)和setValue forKey中子类化NSObject的子类

时间:2015-11-26 16:48:59

标签: ios swift inheritance nsobject

我正在编写一个基类模型类,它是NSObject的子类,然后每个模型都是这个模型的子类。

创建模型时,我提供Dictionary<String, AnyObject>个属性来组成模型属性。

class Model: NSObject {

  var hi: String = "hi"

  init(attributes: Dictionary<String, AnyObject>) {
    super.init()
    for (index, attribute) in attributes {
      self.dynamicType.setValue(attribute, forKey: index)
    }
  }

}

class User: Model {

  var name: String = "Donatello"

}

当我在NSObject的直接子类上执行如下操作时,它可以工作:

let model = Model(attributes: ["hi": "bonjour!"])
print(model.hi) // prints "bonjour!"

甚至在User上做同样的事情,继承自NSObject的类的子类也可以工作:

let model = User(attributes: ["hi": "subclass bonjour!"])
print(model.hi) // prints "subclass bonjour!"

但如果我尝试设置仅在此子类中可用的属性,我会得到经典的this class is not key value coding-compliant for the key name.

例如:

let model = User(attributes: ["name": "Raphael"])

导致错误。

当此对象(作为从NSObject继承的类的子类)应自动从NSObject继承时,为什么会发生此错误。

这是我对子类化的基本理解的问题吗?

1 个答案:

答案 0 :(得分:1)

问题在于您对更基本的东西的理解:类和实例。变化:

  self.dynamicType.setValue(attribute, forKey: index)

为:

  self.setValue(attribute, forKey: index)
相关问题