Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data NSFetchedResultsController - Total number of records returned

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!

like image 837
Neal L Avatar asked Jan 22 '10 00:01

Neal L


4 Answers

This line returns the total number of fetched objects:

[fetchedResultsController.fetchedObjects count]
like image 146
gerry3 Avatar answered Nov 12 '22 23:11

gerry3


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.

like image 39
Max Desiatov Avatar answered Nov 12 '22 23:11

Max Desiatov


Swift.

fetchedResultsController.fetchedObjects?.count

like image 4
jstn Avatar answered Nov 12 '22 22:11

jstn


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)

like image 1
Bill Feth Avatar answered Nov 12 '22 23:11

Bill Feth