iOS 11 NSPredicate search on Swift array crashing - NSUnknownKeyException

后端 未结 1 1920
深忆病人
深忆病人 2021-01-02 19:47

I am using NSPredicate to filter an array in Swift. The problem is after updating to iOS 11 (Xcode 9 /w Swift 4), I keep getting a crash on the filter line. Here is the cras

相关标签:
1条回答
  • 2021-01-02 20:34

    After fighting with this for a while, I finally came across the answer!

    A subtlety of updating to Swift 4 is that classes that are subclasses of NSObject are no longer implicitly exposed to objective-c like they were before. Because of this, you need to explicitly annotate classes/functions with @objc. The compiler will notify you of places where the annotation is needed, but not in this case.

    Ultimately because of this, the key-value lookup was no longer implicitly exposed to objective-c, which is needed to filter with NSPredicate. The code below fixes the crash!

    Solution 1

    extension Model {
        @objc override func value(forKey key: String) -> Any? {
            switch key {
            case "name":
                return name
            default:
                return nil
            }
        }
    }
    

    Solution 2

    Alternative thanks to Uros19: Instead of implementing the above function, you could annotate the property directly with @objc (e.g., @objc let name: String). You lose a little bit of clarity as to why you are annotating the property with @objc, but this is only a small consideration.

    I hope this saves some people time and frustration :)

    0 讨论(0)
提交回复
热议问题