Search code examples
swiftcore-datansfetchrequest

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


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


Solution

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