Core Data NSFetchedResultsController - Total number of records returned

19,043

Solution 1

This line returns the total number of fetched objects:

[fetchedResultsController.fetchedObjects count]

Solution 2

How about this one?

[fetchedResultsController.sections.valueForKeyPath: @"@sum.numberOfObjects"];

This won't touch the fetched objects at all so it's guaranteed not to fault those.

Solution 3

Swift.

fetchedResultsController.fetchedObjects?.count

Solution 4

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)

Share:
19,043
Neal L
Author by

Neal L

Updated on June 02, 2022

Comments

  • Neal L
    Neal L almost 2 years

    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!

  • Neal L
    Neal L over 14 years
    Thanks! I knew it had to be something simple like that!
  • Senseful
    Senseful almost 11 years
    For anyone wondering, if you are using the a Fetch Request's fetch batch size property, accessing this count method above should not fault all of the objects. Reference: developer.apple.com/library/mac/#documentation/Cocoa/Referen‌​ce/…
  • bobics
    bobics almost 11 years
    @Senseful where does it say it won't fault the objects? It's not obvious from the docs. Is this something you tested?
  • memmons
    memmons about 10 years
    @Senseful Also curious about the assertion that fetchedObjects count won't fire faults.
  • pronebird
    pronebird over 8 years
    @mokagio because performFetch already creates faults. Instead of looping through sections which can be incredibly expensive if you have thousands of them, you should simply call count on fetchedObjects.