Sort NSArray with NSDate object into NSDictionary by month

时光总嘲笑我的痴心妄想 提交于 2019-12-11 03:36:21

问题


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?


回答1:


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
   }
}



回答2:


Take a look at NSDateComponents. If you convert your dates to date components:

[[NSCalendar currentCalendar] components:(NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date]

then you'll have objects you can very easily compare for equality.




回答3:


I think, this question was missing answer from Ole Begemann, however this is a link (and I'm not able to post a comment < repo) I'm giving an answer to this question,

If someone still looking for some elegant solution, check this out,

http://oleb.net/blog/2011/12/tutorial-how-to-sort-and-group-uitableview-by-date/



来源:https://stackoverflow.com/questions/14987147/sort-nsarray-with-nsdate-object-into-nsdictionary-by-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!