Reputation: 9466
I have an app that I know the first time it runs there will be nothing saved in CoreData. I am trying to check for that scenario like this:
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)")
}
I get a warning saying "Cast from "Int" to unrelated type '[Person]' always fails.
I'm just not sure what I'm missing. I'm sure checking for any Entities in CoreData is a common practice.
Upvotes: 1
Views: 169
Reputation: 9540
You don't need to convert that into [Entity]
because the countForFetchRequest
returns the number of counts. So, you need need to call without casting.
let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
print("Count \(fetchResults)")
Upvotes: 3
Reputation: 9466
I was able to use this code to get the countForFetchRequest working:` 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)")
}`
Upvotes: 0