core-datansmanagedobjectnsmanagedobjectcontextnspersistentstore

How do I get a fetch request to return the number of objects in the persistent store?


When my app launches and the first view controller is created, a new backing NSManagedObject is also created. At this point, I have NOT saved the context (and I started with a fresh, empty persistent store).

The user can transition to another screen that will show a message if there are no saved items or, if saved items exist, it will show a list of the items. This is how I'm checking for saved items:

func checkForSavedItems() -> Bool {
    var itemsDoExist = false
    let fetchRequest = NSFetchRequest<NSNumber>(entityName: "Items")
    fetchRequest.includesPendingChanges = false
    fetchRequest.resultType = .countResultType

    do {
        let countResult = try context.fetch(fetchRequest)
        itemsDoExist = countResult.first!.intValue > 0
    } catch let error {
        print(error)
    }
    return itemsDoExist
}

I expected that fetchRequest.includesPendingChanges = false would have ensured that the new object that hasn't been saved would not be counted but it is. The count comes back as 1 so it must be counting items in the NSManagedObjectContext

This also suggests that the fetch request is returning the count of items in the context, not the persistent store.

How do I get the real number of items in the persistent store?

Thanks


Solution

  • I also expected that fetchRequest.includesPendingChanges = false would exclude objects that have been inserted in the context but not saved to the store.

    However, the count(for: NSFetchRequest) method should give the correct count. You can find the Apple documentation here.