xcode Swift 4“此类不符合键值编码”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44762460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:05:04  来源:igfitidea点击:

Swift 4 "This class is not key value coding compliant"

iosswiftxcodeswift4

提问by user1537360

I have a Swift library which is heavily reliant on obj.valueForKey()from NSObject.

我有一个雨燕库,是严重依赖obj.valueForKey()NSObject

After migrating to Swift 4 I've found that these calls always crash with the error "this class is not key value coding-compliant for the key..." unless the property I'm looking for is declared with @objc.

迁移到 Swift 4 后,我发现这些调用总是会因错误“此类不是键值编码兼容的键...”而崩溃,除非我要查找的属性是用@objc.

Is it now mandatory to declare properties with @objcfor them to be found with this method? Is there an alternative?

现在是否必须声明属性@objc才能使用此方法找到它们?有替代方案吗?

回答by nathan

When you performed the migration Xcode asked about @objcinference and you probably selected the new type instead of Swift3.

当您执行迁移时 Xcode 询问@objc推理,您可能选择了新类型而不是 Swift3。

Possible solutions:

可能的解决方案:

Use @objc

@objc

Use @objcon each method, as needed instead of the whole class.

@objc根据需要在每个方法上使用,而不是在整个类上使用。

Use @objcMembers

@objcMembers

You could just use @objcMemberson the class.

你可以@objcMembers在课堂上使用。

Applying @objcMembers attribute to a class implicitly adds the @objc attribute to all of its Objective-C compatible members.

Writing Swift Classes and Protocols with Objective-C Behavior

将@objcMembers 属性应用到一个类中会隐式地将@objc 属性添加到它的所有Objective-C 兼容成员中。

使用 Objective-C 行为编写 Swift 类和协议

Keep in mind: because applying the @objc attribute can increase the compiled size of an app and adversely affect performance, only apply the @objcMembers attribute on declarations when each member needs to have the @objc attribute applied.

请记住:因为应用@objc 属性会增加应用程序的编译大小并对性能产生不利影响,所以只有在每个成员需要应用@objc 属性时才在声明上应用@objcMembers 属性

Switch inference to the old behavior

将推理切换到旧行为

You can also change the project's behavior under: Build Settings> Swift 3 @objc Inference> On/Off

您还可以在以下位置更改项目的行为: Build Settings> Swift 3 @objc Inference> On/Off

Related questions:

相关问题: