我正在编写一个基础模型类,它是 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/