当您知道没有保存实体时如何处理 CoreData 中的获取请求
How to handle fetch requests in CoreData when you know there are no Entities saved
我有一个应用程序,我知道它在第一次运行时不会在 CoreData 中保存任何内容。我正在尝试检查这种情况:
let fetchRequest = NSFetchRequest(entityName: "Person")
let error = NSErrorPointer()
do{
let fetchResults = (try! coreDataStack.context.countForFetchRequest(fetchRequest, error: error))
print("Count \(fetchResults)")
} catch let error as NSError{
print("Fetch failed: \(error.localizedDescription)")
}
我收到一条警告,说 "Cast from "Int" to unrelated type '[Person]' 总是失败。
我只是不确定我错过了什么。我确定检查 CoreData 中的任何实体是一种常见做法。
您不需要将其转换为 [Entity]
,因为 countForFetchRequest
returns 计数。因此,您需要在不强制转换的情况下进行调用。
let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
print("Count \(fetchResults)")
我能够使用这段代码让 countForFetchRequest 工作:` let fetchRequest = NSFetchRequest(entityName: "Person")
var error: NSError?
let count = coreDataStack.context.countForFetchRequest(fetchRequest, error: &error)
if count != NSNotFound {
print("Count \(count)")
} else {
print("Could not fetch \(error), \(error?.userInfo)")
}`
我有一个应用程序,我知道它在第一次运行时不会在 CoreData 中保存任何内容。我正在尝试检查这种情况:
let fetchRequest = NSFetchRequest(entityName: "Person")
let error = NSErrorPointer()
do{
let fetchResults = (try! coreDataStack.context.countForFetchRequest(fetchRequest, error: error))
print("Count \(fetchResults)")
} catch let error as NSError{
print("Fetch failed: \(error.localizedDescription)")
}
我收到一条警告,说 "Cast from "Int" to unrelated type '[Person]' 总是失败。
我只是不确定我错过了什么。我确定检查 CoreData 中的任何实体是一种常见做法。
您不需要将其转换为 [Entity]
,因为 countForFetchRequest
returns 计数。因此,您需要在不强制转换的情况下进行调用。
let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
print("Count \(fetchResults)")
我能够使用这段代码让 countForFetchRequest 工作:` let fetchRequest = NSFetchRequest(entityName: "Person")
var error: NSError?
let count = coreDataStack.context.countForFetchRequest(fetchRequest, error: &error)
if count != NSNotFound {
print("Count \(count)")
} else {
print("Could not fetch \(error), \(error?.userInfo)")
}`