2

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]

重複した日付で一致したことはありません。これをきれいに行う方法について誰か考えがありますか?

4

2 に答える 2

0

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];
}
于 2013-01-10T03:17:04.087 に答える
0

だから、実際に私がやったのは、オブジェクトを格納するための配列のディクショナリを作成することでした。ディクショナリの各キーは日で、オブジェクトはオブジェクト (旅行) の配列でした

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];

}
于 2013-01-10T02:31:58.043 に答える