Cocoa Core Data 计算实体的有效方法 [英] Cocoa Core Data efficient way to count entities

查看:16
本文介绍了Cocoa Core Data 计算实体的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多关于 Core Data 的书......但是对实体类型进行计数的有效方法是什么(就像 SQL 可以用 SELECT count(1) ...).现在我刚刚解决了这个任务,用 NSFetchedResultsController 全选并获取 NSArray 的计数!我确定这不是最好的方法...

I read much about Core Data.. but what is an efficient way to make a count over an Entity-Type (like SQL can do with SELECT count(1) ...). Now I just solved this task with selecting all with NSFetchedResultsController and getting the count of the NSArray! I am sure this is not the best way...

推荐答案

我不知道使用 NSFetchedResultsController 是否是实现目标的最有效方式(但可能是).获取实体实例数的显式代码如下:

I don't know whether using NSFetchedResultsController is the most efficient way to accomplish your goal (but it may be). The explicit code to get the count of entity instances is below:

// assuming NSManagedObjectContext *moc

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:moc]];

[request setIncludesSubentities:NO]; //Omit subentities. Default is YES (i.e. include subentities)

NSError *err;
NSUInteger count = [moc countForFetchRequest:request error:&err];
if(count == NSNotFound) {
  //Handle error
}

[request release];

这篇关于Cocoa Core Data 计算实体的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆