我正在尝试找到最有效的方法来对 CoreData 执行提取请求。以前我首先检查是否存在错误,如果不存在我检查返回实体的数组。有没有更快的方法来做到这一点。这样的方式是否可以接受?
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)")
}
}
亲切的问候, 费舍尔
最佳答案
先检查executeFetchRequest()
的返回值是否正确。
如果获取失败,则返回值为 nil
,在这种情况下为错误
变量将被设置,因此无需检查if let error = fetchError
。
请注意,如果不存在(匹配的)对象,请求不会失败。 在这种情况下,将返回一个空数组。
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)")
}
关于swift - 在 CoreData 中执行获取请求的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29602139/