Swift 2.0中的countForFetchRequest [英] countForFetchRequest in Swift 2.0
问题描述
我试图在Swift 2.0中的托管对象上下文上使用countForFetchRequest
方法.
I am trying to use the countForFetchRequest
method on a managed object context in Swift 2.0.
我注意到executeFetchRequest
的错误处理已更改为新的do-try-catch
语法:
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]
,但是countForFetchRequest
方法仍然使用旧式错误指针:
but the countForFetchRequest
method still uses the legacy error pointer:
func countForFetchRequest(_ request: NSFetchRequest,
error error: NSErrorPointer) -> Int
...而且我在弄清楚如何在Swift 2.0中使用此功能时遇到了一些麻烦.
...and I am having a bit of trouble figuring out how to use this in Swift 2.0.
如果我做的是与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)
我收到错误消息说要删除&
,但是如果我删除该消息,我会收到另一个错误消息说NSError
无法转换为NSErrorPointer
.
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.
推荐答案
您的代码几乎是正确的,但是error
必须是变量,以便以
输入&
的inout参数:
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)
更新:自 Swift 3 起,countForFetchRequest
引发错误:
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
}
这篇关于Swift 2.0中的countForFetchRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!