简体   繁体   中英

Core Data - Swift - Catch “keypath not found in entity” error

I am trying to catch an error when I execute a FetchRequest with a wrong/inexistent Key/Keypath but the app still crashes.

This is how I created the NSPredicate:

let pred = NSPredicate(format: "(\("WRONGKEY") = %@)", equalTo)
let request = NSFetchRequest()
request.predicate = pred
request.entity = MyEntityDescription

(WRONGKEY is a parameter that could be wrong/nonexistent in the Core Data schema)

And this is the line that cause the error:

var objects = managedContext?.executeFetchRequest(request, error: &error) as? [Model]

This is the error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath keyX not found in entity < NSSQLEntity EN id=2 >' * First throw call stack: .....

So I have tried to use:

if let objects = managedContext?.executeFetchRequest(request, error: &error) as? [Model] {
    println("okkkkkkkk")
} else {
    println("error")
}

but doesn't work.

I have tried:

if(error != nil) {

but doesn't work either.

Is there a way to catch the error and avoid that the app crashes?

In Swift, try-catch isn't available. You can switch back to Objective-C, or use a library like this one to add the functionality.

That said, your problem can be solved by keeping track of which keys are valid, instead of implementing a try-and-see approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM