在 Swift (iOS) 中继承 NSObject 的子类并为 Key 设置值
Subclassing a subclass of NSObject in Swift (iOS) and setValue forKey
我正在编写一个基础模型 class,它是 NSObject 的子class,然后每个模型都是该模型的子class。
创建模型时,我提供了 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
的直接子 class 上执行以下操作时,它有效:
let model = Model(attributes: ["hi": "bonjour!"])
print(model.hi) // prints "bonjour!"
甚至在 User
上做同样的事情,继承自 NSObject
的 class 的子 class 有效:
let model = User(attributes: ["hi": "subclass bonjour!"])
print(model.hi) // prints "subclass bonjour!"
但是如果我尝试设置仅在该子 class 中可用的属性,我会得到 classic this class is not key value coding-compliant for the key name.
例如:
let model = User(attributes: ["name": "Raphael"])
导致错误。
当此对象作为从 NSObject 继承的 class 的子class 应该自动从 NSObject 继承时,为什么会出现此错误。
这是我对 subclassing 的基本理解有问题吗?
问题在于您对更基本的东西的理解:类 和实例。变化:
self.dynamicType.setValue(attribute, forKey: index)
至:
self.setValue(attribute, forKey: index)
我正在编写一个基础模型 class,它是 NSObject 的子class,然后每个模型都是该模型的子class。
创建模型时,我提供了 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
的直接子 class 上执行以下操作时,它有效:
let model = Model(attributes: ["hi": "bonjour!"])
print(model.hi) // prints "bonjour!"
甚至在 User
上做同样的事情,继承自 NSObject
的 class 的子 class 有效:
let model = User(attributes: ["hi": "subclass bonjour!"])
print(model.hi) // prints "subclass bonjour!"
但是如果我尝试设置仅在该子 class 中可用的属性,我会得到 classic this class is not key value coding-compliant for the key name.
例如:
let model = User(attributes: ["name": "Raphael"])
导致错误。
当此对象作为从 NSObject 继承的 class 的子class 应该自动从 NSObject 继承时,为什么会出现此错误。
这是我对 subclassing 的基本理解有问题吗?
问题在于您对更基本的东西的理解:类 和实例。变化:
self.dynamicType.setValue(attribute, forKey: index)
至:
self.setValue(attribute, forKey: index)