我有以下用例:
class Foo: NSObject {
var bar = ""
}
let foo = Foo()
foo.setValue("A name", forKey: "bar") //throws exception: this class is not key value coding-compliant for the key bar.
print("Foo.bar: \(foo.bar)")
Apple文档(here)表示,在Swift中,每个包含NSObject的类在默认情况下都符合键值。如果是这样,为什么我没有获得键值兼容的异常?Swift objects that inherit from NSObject or one of its subclasses are key-value coding compliant for their properties by default.
我想念什么吗?有人知道这可能是问题吗?
注意:我试图使“bar”属性为NSString,但是出现了同样的异常。
最佳答案
为属性实现KVC(键值编码)支持。
您需要在媒体资源上添加 @objc 批注,
由于KVC的当前实现是用Objective-C编写的,因此在添加 @objc 之后,Objective-c可以看到它。
class Foo: NSObject {
@objc var bar = ""
}
let foo = Foo()
foo.setValue("A name", forKey: "bar")
print("Foo.bar: \(foo.bar)")
关于ios - setValue:forKey总是 swift 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693633/