核心数据 - Swift - 捕获 "keypath not found in entity" 错误

Core Data - Swift - Catch "keypath not found in entity" error

我试图在使用 wrong/inexistent Key/Keypath 执行 FetchRequest 时捕获错误,但应用程序仍然崩溃。

这就是我创建 NSPredicate 的方式:

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

(WRONGKEY 是一个参数,在 Core Data 模式中可能是 wrong/nonexistent)

这是导致错误的行:

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

这是错误:

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

所以我尝试使用:

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

但不起作用。

我试过:

if(error != nil) {

但也不起作用。

有没有办法捕获错误并避免应用程序崩溃?

在 Swift 中,try-catch 不可用。您可以切换回 Objective-C,或使用 library like this one 添加功能。

也就是说,您的问题可以通过跟踪哪些密钥有效来解决,而不是实施试一试的方法。