Florin
Florin

Reputation: 2981

NSFetchRequest group by month

In my model, I have a Sale entity, each Sale entity has a date property (NSDate). I want to compute the sum of sales for each month.

I know how to create the expression for computing the sum, what I want to find out is how do I tell NSFetchRequest to group by month.

Upvotes: 0

Views: 1132

Answers (1)

Mundi
Mundi

Reputation: 80271

You can use a NSFetchedResultsController to do the grouping for you. It has a parameter in the factory method called sectionNameKeyPath which you can use to separate your data. You will get all the NSIndexPath arithmetic for free, and a myriad of optimizations as well.

Because dates are practically continuous, you have to work with transient properties, or even persist the month data (which is cheap, so it does not matter). Take a look at Apple's sample code with dates in section headers and proceed analogously.

Apple Sample Code: DateSectionTitles
Pay particular attention to the implementation of APLEvent.

Upvotes: 5

Related Questions