Nic*_*ard 2 cocoa-touch objective-c nsdictionary nsarray ios
我正在构建一个UITableView并希望按月分组,以便我可以将这些字符串作为我的节标题,例如:
February 2013
- Item 1
- Item 2
January 2013
- Item 1
- Item 2
Run Code Online (Sandbox Code Playgroud)
我有一个NSArray自定义对象,其pubDate属性是一个NSDate.
如何使用该NSDate对象将我的自定义对象NSDictionary按月分组?
像这样排序数组
NSArray *sortedArray = [yourArrayOfCustomObjects sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate *firstDate = [(YourCustomObject*)obj1 pubDate];
NSDate *secondDate = [(YourCustomObject*)obj2 pubDate];
return [firstDate compare:secondDate];
}];
Run Code Online (Sandbox Code Playgroud)
//现在进行简单的迭代,您可以确定所有相同月份的条目.
//代码不完整仅用于说明目的.
//您还必须处理年度变化.
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3615 次 |
| 最近记录: |