Swift 4 "This class is not key value coding compliant"
I have a Swift library which is heavily reliant on obj.valueForKey()
from 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
.
Is it now mandatory to declare properties with @objc
for them to be found with this method? Is there an alternative?
Solution 1:
When you performed the migration Xcode asked about @objc
inference and you probably selected the new type instead of Swift3.
Possible solutions:
Use @objc
Use @objc
on each method, as needed instead of the whole class.
Use @objcMembers
You could just use @objcMembers
on the class.
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
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.
Switch inference to the old behavior
You can also change the project's behavior under:
Build Settings
> Swift 3 @objc Inference
> On
/Off
Related questions:
- The use of Swift 3 @objc inference in Swift 4 mode is deprecated?
- How can I deal with @objc inference deprecation with #selector() in Swift 4?