iOS 11 NSPredicate search on Swift array crashing - NSUnknownKeyException

隐身守侯 提交于 2019-12-19 02:54:11

问题


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 crash log:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: >'[ valueForUndefinedKey:]: this class is not key >value coding-compliant for the key name.'

Here is an example of the class that I have an array of:

final class Model: NSObject {
    let name: String
    init(name: String) {
        self.name = name
    }
}

Here is the code that is crashing:

let myArray = [Model(name: "Jason"), Model(name: "Brian")]
let predicate = NSPredicate(format: "name == 'Jason'")
let filteredArray = myArray.filter { predicate.evaluate(with: $0)}

Question is why is this crashing now that I updated to iOS 11?


回答1:


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 :)



来源:https://stackoverflow.com/questions/46371156/ios-11-nspredicate-search-on-swift-array-crashing-nsunknownkeyexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!