Grouping Core Data Objects
I have a core data entity that has a created_at attribute which is a NSDate, and an amount attribute which is a NSInteger.
I would like to make a request that returns the sum of amounts grouped by months. Something like:
[['February 2010', 450], ['January 2010', 300]]
开发者_JS百科
I'm not sure how to approach this, if I would have to first fetch all results for a specific date range, and then calculate sum, or if there are other methods.
P.S. I'm doing this on the iphone 4.2 sdk.
Even thought an answer has already be accepted let me add this more sophisticated and faster method for completeness.
Assuming the months aren't modeled in your data model, you will need to fetch the objects in each month and then sum the amounts. Repeat for as many months as you need.
So, the first step is to create a variable predicate for the fetch. Something like this:
NSPredicate *exPred=[NSPredicate predicateWithFormat:@"%@<=created_at<=%@", monthStartDate,monthEndDate];
NSPredicate *exPred=[NSPredicate predicateWithFormat:@"(%@<=created_at) AND (created_at<=%@)", monthStartDate,monthEndDate];
... then execute the fetch and sum the return:
NSNumber *theSum=[@sum.[context executeFetchRequest:theFetch error:&error].amount];
... or less cowboy:
NSArray *fetchedObjects=[context executeFetchRequest:theFetch error:&error];
// if no error
NSNumber *theSum=[fetchedObjects valueForKeyPath:@"@sum.amount"];
Put that in a loop for each month.
Predicates and collection operates are much faster than loops. Use them instead of loops whenever possible.
I'd fetch the range of objects you're interested into an array, then enumerate through that array and add all the amounts up on the go.
I'm not sure if this could be solved by creating a sophisticated request too, but my gut feeling tells me it would be tricky to set up anyway (if possible at all)...
精彩评论