countForFetchRequest in Swift 2.0

萝らか妹 提交于 2019-12-21 09:35:21

问题


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 has been changed across to the new do-try-catch syntax:

func executeFetchRequest(_ request: NSFetchRequest) throws -> [AnyObject]

but the countForFetchRequest method still uses the legacy error pointer:

func countForFetchRequest(_ request: NSFetchRequest,
                    error error: NSErrorPointer) -> Int

...and I am having a bit of trouble figuring out how to use this in Swift 2.0.

If I do the same thing as pre-Swift 2.0:

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

I get errors saying to remove the &, but if I remove that I get another error saying that NSError cannot be converted to an NSErrorPointer.

Any help would be appreciated about how to get this working.


回答1:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/34652618/countforfetchrequest-in-swift-2-0

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