我正在构建一个 UITableView
并想按月分组,这样我就可以将这些字符串作为我的部分标题,例如:
February 2013
- Item 1
- Item 2
January 2013
- Item 1
- Item 2
我有一个 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];
}];
//现在是一个简单的迭代,您可以确定所有相同月份的条目。
//代码并不完整,仅供说明之用。
//你还必须处理年份变化。
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
}
}
关于ios - 按月将带有 NSDate 对象的 NSArray 排序到 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987147/