【问题标题】:Sort NSArray with NSDate object into NSDictionary by month按月将带有 NSDate 对象的 NSArray 排序到 NSDictionary
【发布时间】:2013-02-05 21:14:18
【问题描述】:

我正在构建一个 UITableView 并希望按月分组,以便我可以将这些字符串作为我的部分标题,例如:

February 2013
- Item 1
- Item 2

January 2013
- Item 1
- Item 2

我有一个 NSArray,它有一个自定义对象,该对象的 pubDate 属性是一个 NSDate

如何使用 NSDate 对象将我的自定义对象按月分组为 NSDictionary

【问题讨论】:

  • 您可以使用内置的数组排序例程非常简单地对日期数组进行排序(如果它是纯粹的 NSDate 对象)。然后“遍历”数组并注意新月份何时开始,添加适当的月份标题。
  • 不,数组中填充了自定义对象,其中一个属性是NSDate
  • 那么它需要通过几种数组排序方法之一来描述日期的路径。只是稍微复杂一点。
  • @NicHubbard 你得到答案了吗?我的要求和你一样。请让我知道我怎样才能达到你的问题的结果?

标签: ios objective-c cocoa-touch nsarray nsdictionary


【解决方案1】:

这样排列数组

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
   }
}

【讨论】:

    【解决方案2】:

    看看NSDateComponents。如果您将日期转换为日期组件:

    [[NSCalendar currentCalendar] components:(NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date]
    

    然后您将拥有可以非常轻松地比较是否相等的对象。

    【讨论】:

      【解决方案3】:

      我认为,这个问题缺少 Ole Begemann 的答案,但是这是一个链接(我无法发表评论

      如果有人仍在寻找优雅的解决方案,请查看此内容,

      http://oleb.net/blog/2011/12/tutorial-how-to-sort-and-group-uitableview-by-date/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-30
        • 2014-09-01
        相关资源
        最近更新 更多