NSFetchRequest for groupby and count combination

不打扰是莪最后的温柔 提交于 2019-12-20 07:11:56

问题


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

回答1:


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.

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"];

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".

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];

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.



来源:https://stackoverflow.com/questions/16917723/nsfetchrequest-for-groupby-and-count-combination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!