开发者

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 c开发者_JAVA技巧ount, can it be done in one line?

Thanks!


This line returns the total number of fetched objects:

[fetchedResultsController.fetchedObjects count]


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.


Swift.

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜