简体   繁体   English

核心数据NSFetchedResultsController - 返回的记录总数

[英]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. 我在iPhone应用程序中使用NSFetchedResultsController,我想知道是否有一些简单的方法来获取所有部分返回的总行数。

Instead of getting the [[fetchedResultsController sections] count] and then looping through each section to get its count, can it be done in one line? 而不是获取[[fetchedResultsController sections] count]然后循环遍历每个部分以获得它的计数,它可以在一行中完成吗?

Thanks! 谢谢!

该行返回获取对象的总数:

[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. 这根本不会触及所取出的物体,所以保证不会对它们造成错误。

迅速。

fetchedResultsController.fetchedObjects?.count

Swift 4: 斯威夫特4:

Max Desiatov's suggestion as a Swift extension: Max Desiatov作为Swift扩展的建议:

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: 注意:需要@objc来避免此编译错误:

Extension of a generic Objective-C class cannot access the class's generic parameters at runtime 泛型Objective-C类的扩展无法在运行时访问类的泛型参数

(See How to write an extension for NSFetchedResultsController in Swift 4 ) (请参阅如何在Swift 4中编写NSFetchedResultsController的扩展

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM