在Swift(iOS)和setValue forKey中对NSObject的子类进行子类化
我正在编写一个基本模型类,它是NSObject的子类,然后每个模型都是这个模型的子类 创建模型时,我提供了一个属性的在Swift(iOS)和setValue forKey中对NSObject的子类进行子类化,ios,swift,inheritance,nsobject,Ios,Swift,Inheritance,Nsobject,我正在编写一个基本模型类,它是NSObject的子类,然后每个模型都是这个模型的子类 创建模型时,我提供了一个属性的字典,以构成模型属性 class Model: NSObject { var hi: String = "hi" init(attributes: Dictionary<String, AnyObject>) { super.init() for (index, attribute) in attributes { self.dy
字典
,以构成模型属性
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"
}
即使在User
上执行同样的操作,继承自NSObject
的类的子类也可以工作:
let model = User(attributes: ["hi": "subclass bonjour!"])
print(model.hi) // prints "subclass bonjour!"
但是如果我尝试设置仅在这个子类中可用的属性,我会得到经典的这个类不符合键值编码的键名。
例如:
let model = User(attributes: ["name": "Raphael"])
导致错误
当此对象作为从NSObject继承的类的子类自动从NSObject继承时,为什么会发生此错误
这是我对子类化的基本理解的问题吗?问题在于你对更基本的东西的理解:类和实例。更改:
self.dynamicType.setValue(attribute, forKey: index)
致:
作品我发誓我试过了,因为我只是在事后才查到dynamicType。。。但很明显,我的理解是有缺陷的。非常感谢,不用担心。这个问题问得很好,不过下次不要在问题中键入非编译代码(而是复制和粘贴)-您在最后一行测试中忽略了
属性:
。请记住,大多数回答者会立即将您的代码复制出来并粘贴到Xcode中,因此您希望它是正确的代码。:)我注意到你为我做了编辑,脸也相应地掌心了!下次我会把你的意见写在黑板上,谢谢。
self.dynamicType.setValue(attribute, forKey: index)
self.setValue(attribute, forKey: index)