【问题标题】:Create UITableView Section for unique dates为唯一日期创建 UITableView 部分
【发布时间】:2013-01-10 02:14:02
【问题描述】:

我希望在 UITableView 中为每个唯一日期创建一个部分。

我的数据被格式化为一个对象数组,每个对象都包含一个NSDate

最初,我使用 dateFormatter @"yyyy-MM-dd" 将每个日期转换为字符串,并相应地比较日期字符串。但这很慢,而且似乎是错误的方式。

我还尝试使用以下方法从NSDate 中删除时间:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: trip.startTime];
[components setHour: 0];
[components setMinute: 0];
[components setSecond: 0];
NSDate *newDate = [gregorian dateFromComponents: components];

但是在使用数组函数时:

[allDays indexOfObject:newDate]

我从来没有遇到过重复日期的比赛。有没有人知道如何干净地做到这一点?

【问题讨论】:

  • 如果您可以封装日期,并且需要订购,请覆盖 compare: 并使用 NSSet 快速唯一化。

标签: ios objective-c uitableview nsdate


【解决方案1】:

所以,实际上我最终做的是创建一个数组字典来存储我的对象。 字典中的每个键都是一天,对象是我的对象数组(行程)

for(Trip *trip in allTrips)
{

    NSString *dateString = [self dayString:trip.startTime];
    NSMutableArray *dayArray = [dict objectForKey:dateString];

    //is the day in the dictionary?
    if (dayArray == nil)
    {
        //This day is not in the dictionary

        //create an empty array
        dayArray = [[NSMutableArray alloc]init];

        //add the array to the dictionary
        [dict setObject:dayArray forKey:dateString];

    }

    //add the trip to the array
    [dayArray addObject:trip];

}

【讨论】:

    【解决方案2】:

    indexOfObject: 使用isEqual: 方法来比较对象。所以你可以在自定义子类中覆盖它:

    - (BOOL) isEqual:(id)object
    {
        NSDateComponents* c1= [[NSCalendar currentCalendar]  components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate: self ];
        NSDateComponents* c2= [[NSCalendar currentCalendar]  components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate: object ];
        return [c1 isEqual: c2];
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多