Sort NSArray with NSDate object into NSDictionary by month

cocoa-touch, ios, nsarray, nsdictionary, objective-c

Solution

Sort array like this

NSArray *sortedArray = [yourArrayOfCustomObjects sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate *firstDate = [(YourCustomObject*)obj1 pubDate];
        NSDate *secondDate = [(YourCustomObject*)obj2 pubDate];
        return [firstDate compare:secondDate];        

    }];

// Now a simple iteration and you can determine all same month entries.

// Code is not complete just for illustration purpose.

// You have to handle Year change as well.

int curMonth = 0;
int prevMonth = 0;
foreach(CustomObject *obj in sortedArray)
{
   NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:obj.pubDate];
   prevMonth = curMonth; 
   curMonth = components.month;
   if(prevMonth != 0 && curMonth != prevMonth)
   {
      //Month Changed
   }
}

Problem

I am building a `UITableView` and would like to group by month so that I can have those strings as my section headers, e.g.: ``` February 2013 - Item 1 - Item 2 January 2013 - Item 1 - Item 2 ``` I have an `NSArray` which has custom objects that have a pubDate property that is an `NSDate`. How can I use that `NSDate` object to group my custom objects into a `NSDictionary` by month?

Original source