且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-09 15:51:07

首先检查 executeFetchRequest()的返回值是否正确。
如果读取失败,则返回值为 nil ,在这种情况下,将设置错误
变量,因此不需要检查如果let error = fetchError

Checking the return value of executeFetchRequest() first is correct. The return value is nil if the fetch failed, in that case the error variable will be set, so there is no need to check if let error = fetchError.

请注意, )对象存在。
在这种情况下,返回一个空数组。

Note that the request does not fail if no (matching) object exist. In that case an empty array is 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)")
}