Search code examples
iosswiftcore-dataswift2nsfetchrequest

How to handle fetch requests in CoreData when you know there are no Entities saved


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.


Solution

  • 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)")