countForFetchRequest in Swift 2.0

前端 未结 2 1910
耶瑟儿~
耶瑟儿~ 2021-02-20 10:48

I am trying to use the countForFetchRequest method on a managed object context in Swift 2.0.

I note that the error handling for executeFetchRequest

相关标签:
2条回答
  • 2021-02-20 11:00

    You need to do like this:

    let error = NSErrorPointer()
    let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
    print("Count \(fetchResults)")
    

    This is the code for Swift 2.0

    0 讨论(0)
  • 2021-02-20 11:01

    Your code is almost correct, but error needs to be a variable, in order to be passed as inout-argument with &:

    var error: NSError? = nil
    let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
    

    Update: As of Swift 3, countForFetchRequest throws an error:

    do {
        let count = try managedObjectContext.context.count(for:fetchRequest)
        return count
    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
        return 0
    }
    
    0 讨论(0)
提交回复
热议问题