A somewhat different method to Matthias's, though I don't see any good way to do this with NSPredicate
either, since date arithmetic is required here.
This creates date components from each date initially and counts those using NSCountedSet
. (You might be able to use a predicate on the counted set.) Then you create another NSDateComponents
object describing the month and year you are interested in, and simply query the set using countForObject:
NSArray * dates = @[/* Your dates here */];
NSCalendar * cal = [NSCalendar currentCalendar];
/* Convert the dates into date components objects for month and year. */
NSMutableArray * months = [NSMutableArray array];
for( NSDate * date in dates ){
NSDateComponents * month = [cal components:(NSMonthCalendarUnit|NSYearCalendarUnit)
fromDate:date];
[months addObject:month];
}
/* Count the unique components. */
NSCountedSet * monthsCounts = [NSCountedSet setWithArray:months];
/* Use a predicate here on the set? */
/* A components object for month arithmetic. */
NSDateComponents * monthDelta = [NSDateComponents new];
/* Get month names for the current locale. */
NSDateFormatter * formatter = [NSDateFormatter new];
NSArray * monthNames = [formatter monthSymbols];
for( NSInteger i = 0; i > -NUM_MONTHS; i-- ){
/* Couting backwards from the current month, get a date components
* object for each month and year.
*/
[monthDelta setMonth:i];
NSDateComponents * currMonth;
currMonth = [cal components:(NSMonthCalendarUnit|NSYearCalendarUnit)
fromDate:[cal dateByAddingComponents:monthDelta
toDate:[NSDate date]
options:0]];
/* Get the count from the counted set and display. */
NSUInteger count = [monthsCounts countForObject:currMonth];
NSLog(@"%lu dates in %@", count,
[monthNames objectAtIndex:[currMonth month] - 1]);
}