NSFetchRequest for groupby and count combination
Asked Answered
P

1

0

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
Pleasance answered 4/6, 2013 at 12:22 Comment(0)
T
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.

Trader answered 4/6, 2013 at 14:32 Comment(3)
so if i have two products, the first is registered from beginning of the day and the second one is registered at the end of the day, i will have two sections right ? is there any comparison predicate to override date comparison?Pleasance
also is there any technique to do a lazy loading on each section ?Pleasance
1) You should create a separate attribute for just the date. You could use a fetched property (which computes on the fly). See Apple's sample code "DateSectionTitles" available here. 2) Lazy loading included automatically in fetched results controller ;-))!Trader

© 2022 - 2024 — McMap. All rights reserved.