NSFetchRequest for groupby and count combination

2020-05-06 11:31发布

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条回答
看我几分像从前
2楼-- · 2020-05-06 11:58

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.

查看更多
登录 后发表回答