NSFetchRequest用于分组和计数组合 [英] NSFetchRequest for groupby and count combination

查看:98
本文介绍了NSFetchRequest用于分组和计数组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Core Data的新手,所以我想编写一个简单的提取请求,以便按某个字段以及该字段中另一个字段的数量对结果进行分组。
,例如,我有产品表,我想按日期和产品数量检索所有分组的产品,在sql中的简单查询就像

I'm new in Core Data, so i want to write simple fetch request to group result by some field and also a count of another field in that group. so for example i have products table i want to retrieve all grouped products by date and the count of product, the simple query in sql is like

SELECT DateRegistered,Count(*) FROM Products  Group By DateRegistered


推荐答案

最好的选择是非常灵活的 NSFetchedResultsController 。您将有一个获取请求,该请求仅获取按date属性排序的Product实体。请注意,核心数据属性应以小写字母开头。

Your best bet is the very flexible NSFetchedResultsController. You would have a fetch request that simply fetches the Product entity sorted by the date attribute. Please note that core data attributes should start with a small letter.

您将使用以下内容创建获取的结果控制器。签出通常在视图控制器中延迟创建的Apple示例代码(包括Xcode模板):

You would create the fetched results controller with something like the following. Check out the Apple sample codes (including the Xcode templates) where this is typically created lazily in the view controller:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Product"];
request.sortDescriptors = @[ [NSSortDescriptor 
             sortDescriptorWithKey:@"dateRegistered"
             ascending:YES] ];


_fetchedResultsController  = [NSFetchedResultsController
   initWithFetchRequest:request
   managedObjectContext:self.managedObjectContext
   sectionNameKeyPath:@"dateRegistered"
   cacheName:"Root"];

这仅在每天的日期确实相同的情况下才有效。对于 NSDate 类型,您可能希望为此使用一个字符串,这样可以精确地分割秒数,并且每个组中的计数都为1。

This will only work if the dates are indeed the same for each day. You probably want to use a string for that for an NSDate type will be accurate to split seconds and you will a count of one in each "group".

使用获取的结果控制器,您可以轻松访问所需的所有数字。例如。 组编号 i 的计数(正确的术语是节):

With the fetched results controller you can easily access all the numbers you want. E.g. the count of "group" number i (the correct terminology is "section"):

id <NSFetchedResultsSectionInfo> sectionInfo = 
       [[_fetchedResultsController sections] objectAtIndex:i];
int count = [sectionInfo numberOfObjects];

您可以使用获取的结果控制器执行更多操作!它会为您管理内存,促进在UI中显示(例如表视图或集合视图),并最大程度地减少对持久性存储的压力。

You can do much more with the fetched results controller! It will manage memory for you, facilitate display in your UI (such as table views or collection views) and minimize the strain on your persistent store.

这篇关于NSFetchRequest用于分组和计数组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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