我有以下VC:错误时调用self.setValue(:forKey :)
class ViewController: UIViewController {
var platforms = [Platform]()
viewDidLoad() {
let newPlatforms = [Platform(0), Platform(1)]
self.setValue(newPlatforms, forKey: "platforms")
}
}
,但在运行时我得到崩溃错误:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: this class is not key value coding-compliant for the key platforms
但其确定当我使用,例如,字符串变量
class ViewController: UIViewController {
var string = ""
viewDidLoad() {
let newString = "Hello world"
self.setValue(newString, forKey: "string")
}
}
我真的需要这种键值编码机制。这个例子特别简化了。
你为什么使用'setValue(_:forKey:)'? – nhgrif
根据这篇文章,观察值('platforms')需要从NSObject继承,并且由于Swift数组甚至不是一个类,它是一个结构体,它可能无法被观察到。 https://medium.com/proto-venture-technology/the-state-of-kvo-in-swift-aa5cb1e05cba#.tse34ddpo – EmilioPelaez