ios - 按月将带有 NSDate 对象的 NSArray 排序到 NSDictionary

标签 ios objective-c cocoa-touch nsarray nsdictionary

我正在构建一个 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/

相关文章:

ios - 如何从导航栏中删除阴影线?

ios - 当 AVPlayer 准备好播放时,addObserver 到 AVPlayer 永远不会被调用?

ios - iPad 视频尺寸/格式

iphone - Core Text - 小框文本太多 - 如何添加三个点?

ios - swift 关闭奇怪的行为

objective-c - 访问文档目录时索引 0 超出空数组的范围

iphone - UITableView 分隔线短暂地穿过覆盖的 UIView

ios - 为什么 becomeFirstResponder 不起作用?

iphone - 传递方法 - Objective-C

iphone - 关于 Objective-C/Cocoa 键值编码和数组