[英]setValue:forKey is always crashing in swift
I have below use case:我有以下用例:
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 documentation ( here ) sais that in Swift each class subclasing NSObject becomes by default key value compliant. Apple 文档( 此处)指出,在 Swift 中,每个 class 子类化 NSObject 默认符合键值。 If so why am I getting not key value compliant exception?如果是这样,为什么我得到不符合键值的异常?
Swift objects that inherit from NSObject or one of its subclasses are key-value coding compliant for their properties by default.继承自 NSObject 或其子类之一的 Swift 对象默认情况下符合其属性的键值编码。
Am I missing something?我错过了什么吗? Dose any one know which could be the problem?任何人都知道这可能是问题吗?
Note: I tried to make the "bar" property NSString but i got the same exception.注意:我试图制作“bar”属性 NSString 但我得到了同样的例外。
To implement KVC(Key-Value Coding) support for a property.为属性实现 KVC(键值编码)支持。 you need the @objc annotation on your property, Since the current implementation of KVC is written in Objective-C, After adding @objc , Objective-c can see it.你的属性需要@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)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.