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

自闭症网瘾萝莉.ら 提交于 2020-01-11 13:03:54

问题


I'm trying to find the most efficient way to do a fetch request against CoreData. Previously I have first checked if an error existed, and if it did not I have checked the array of the returned entity. Is there a quicker way to do this. Is something like this an accepted way to do the request?

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

    }
}

Kind Regards, Fisher


回答1:


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)")
}


来源:https://stackoverflow.com/questions/29602139/what-is-the-best-way-to-do-a-fetch-request-in-coredata

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