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

标签 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会出现这个错误。

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

最佳答案

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

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

到:

  self.setValue(attribute, forKey: index)

关于ios - 在 Swift(iOS)和 setValue forKey 中子类化 NSObject 的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33943630/

相关文章:

iphone - 在 iOS 中将日期格式化为 dd-MMM

iphone - 尝试通过 NSKeyedArchiver 将用户数据保存到文件 - NSInvalidArgumentException 是我单击“保存”时得到的结果

swift - 我怎样才能找到给定数字 N 中有多少个有用的数字

swift - 使用 Swift 计算属性 vs.访问器和修改器函数

java - 继承和接口(interface)背景下协议(protocol)和契约的含义

java - 如何让子类用扩展类型重写父类抽象方法?

iphone - 从URL下载图像时如何使用UIactivityindicatorview

swift - 如何将经纬度传递给 APIURL?

c++ - C++ 中基类地址的保证?

ios - 在 iOS 中使用静态单元格时如何访问 tableviewcell 附件详细信息?