[英]Subclassing a subclass of NSObject in Swift (iOS) and setValue forKey
I am writing a base model class which subclasses NSObject, and then each model will be a subclass of this model.我正在编写一个基模型类,它是 NSObject 的子类,然后每个模型都将是该模型的子类。
When creating a model I provide a Dictionary<String, AnyObject>
of attributes to make up the model properties.创建模型时,我提供了一个
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"
}
When I do as below on the direct subclass of NSObject
, it works:当我对
NSObject
的直接子类执行以下操作时,它可以工作:
let model = Model(attributes: ["hi": "bonjour!"])
print(model.hi) // prints "bonjour!"
and even doing the same on User
, the subclass of a class inheriting from NSObject
works:甚至在
User
上做同样的事情,从NSObject
继承的类的子类工作:
let model = User(attributes: ["hi": "subclass bonjour!"])
print(model.hi) // prints "subclass bonjour!"
but if I try setting properties only available in this subclass, I get the classic this class is not key value coding-compliant for the key name.
但是如果我尝试设置仅在此子类中可用的属性,我会得到经典的
this class is not key value coding-compliant for the key name.
for example:例如:
let model = User(attributes: ["name": "Raphael"])
causes error.导致错误。
Why does this error occur when this object, as a subclass of a class inheriting from NSObject, should inherit from NSObject automatically.这个对象作为从NSObject继承的类的子类,应该自动从NSObject继承时,为什么会出现这个错误。
Is this a problem with my fundamental understanding of subclassing?这是我对子类化的基本理解的问题吗?
The problem is with your understanding of something much more basic: classes and instances.问题在于您对更基本的东西的理解:类和实例。 Change:
改变:
self.dynamicType.setValue(attribute, forKey: index)
to:到:
self.setValue(attribute, forKey: index)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.