Core Data NSFetchedResultsController - Total number of records returned

Viewed 19167

I'm using an NSFetchedResultsController in an iPhone app, and am wondering if there is some easy way of getting the total number of rows returned in all sections.

Instead of getting the [[fetchedResultsController sections] count] and then looping through each section to get its count, can it be done in one line?

Thanks!

4 Answers

This line returns the total number of fetched objects:

[fetchedResultsController.fetchedObjects count]

Swift 4:

Max Desiatov's suggestion as a Swift extension:

import Foundation
import CoreData

extension NSFetchedResultsController {

    @objc var fetchedObjectsCount: Int {
        // Avoid actually fetching the objects. Just count them. Why is there no API like this on NSFetchResultsController?
        let count = sections?.reduce(0, { (sum, sectionInfo) -> Int in
            return sum + sectionInfo.numberOfObjects
        }) ?? 0
        return count
    }
}

Usage:

let objectCount = fetchedResultsController.fetchedObjectCount

Or do it as an inline routine:

// Avoid actually fetching objects. Just count them.
let objectCount = fetchedResultsController.sections?.reduce(0, { $0 + $1.numberOfObjects }) ?? 0

Note: The @objc is needed to avoid this compile error:

Extension of a generic Objective-C class cannot access the class's generic parameters at runtime

(See How to write an extension for NSFetchedResultsController in Swift 4)

Related