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

前端 未结 1 1854
名媛妹妹
名媛妹妹 2021-01-27 11:32

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 arra

相关标签:
1条回答
  • 2021-01-27 12:01

    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)")
    }
    
    0 讨论(0)
提交回复
热议问题