在 CoreData 中执行获取请求的最佳方法是什么?

What is the best way to do a fetch request in CoreData?

我正在尝试找到对 CoreData 执行提取请求的最有效方法。以前我首先检查是否存在错误,如果不存在我检查返回实体的数组。有没有更快的方法来做到这一点。这样的方式是否可以接受?

let personsRequest = NSFetchRequest(entityName: "Person")

var fetchError : NSError?

//Is it okay to do the fetch request like this? What is more efficient?
if let personResult = managedObjectContext.executeFetchRequest(personRequest, error: &fetchError) as? [Person] {

    println("Persons found: \(personResult.count)")

}
else {

    println("Request returned no persons.")

    if let error = fetchError {

        println("Reason: \(error.localizedDescription)")

    }
}

亲切的问候, 费舍尔

首先检查executeFetchRequest()的return值是正确的。 如果获取失败,return 值为 nil,在这种情况下会出现错误 变量 将被设置 ,因此无需检查 if let error = fetchError

请注意,如果不存在(匹配的)对象,请求不会失败。 在那种情况下,一个空数组是 returned.

let personRequest = NSFetchRequest(entityName: "Person")
var fetchError : NSError?
if let personResult = managedObjectContext.executeFetchRequest(personRequest, error: &fetchError) as? [Person] {
    if personResult.count == 0 {
        println("No person found")
    } else {
        println("Persons found: \(personResult.count)")
    }
} else {
    println("fetch failed: \(fetchError!.localizedDescription)")
}