按月将带有NSDate对象的NSArray排序为NSDictionary [英] Sort NSArray with NSDate object into NSDictionary by month
本文介绍了按月将带有NSDate对象的NSArray排序为NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建 UITableView
,并希望按月分组,以便我可以将这些字符串作为我的节标题,例如:
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
我有 NSArray
具有自定义对象,这些对象的pubDate属性为 NSDate
。
I have an NSArray
which has custom objects that have a pubDate property that is an NSDate
.
如何使用 NSDate
对象将我的自定义对象按月分组为 NSDictionary
?
How can I use that NSDate
object to group my custom objects into a NSDictionary
by month?
推荐答案
像这样排序数组
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.
//您还必须处理Year更改。
// 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
}
}
这篇关于按月将带有NSDate对象的NSArray排序为NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文