问题
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