2

NSFetchedResultsControllerとNSSortDescriptorを使用して、各日付のセクションを持つテーブルに正常に並べ替えているので、今日の日付が最初に表示されます(日付の降順)。

ただし、そのセクションでは、時間を昇順で並べ替えてほしいと思います。

これは、時間でソートしない現在のコードです。

//Set up the fetched results controller.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:kEntityHistory inManagedObjectContext:global.managedObjectContext];
fetchRequest.entity = entity;

// Sort using the timeStamp property..
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

fetchRequest.sortDescriptors = sortDescriptors;

//The following is from:
//http://stackoverflow.com/questions/7047943/efficient-way-to-update-table-section-headers-using-core-data-entities

NSString *sortPath = @"date.dayDate";

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:global.managedObjectContext sectionNameKeyPath:sortPath cacheName:nil];

fetchedResultsController.delegate = self;

この日付セクション内で時間の昇順で並べ替えを追加するようにコードを変更するにはどうすればよいですか?

4

1 に答える 1

3

これには特別なコンパレータが必要だと思います。initWithKey:ascending:comparator:を使用してソート記述子を初期化し、コンパレータとして次を渡します。

^(id obj1, id obj2) {
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSHourCalendarUnit|NSDayCalendarUnit fromDate:obj1];
    NSInteger day1 = [components1 day];
    NSInteger hour1 = [components1 hour];

    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSHourCalendarUnit|NSDayCalendarUnit fromDate:obj2];
    NSInteger day2 = [components2 day];
    NSInteger hour2 = [components2 hour];

    NSComparisonResult res;
    if (day1>day2) {
        res = NSOrderedAscending;
    } else if (day1<day2) {
        res = NSOrderedDescending;
    } else {
        if (hour1>hour2) {
            res = NSOrderedDescending;
        } else {
            res = NSOrderedAscending;
        }
    }
    return res;
}

これにより、これをどのように実現できるかがわかります。分と秒のコンポーネントを追加する必要があります。また、時間、分、秒が等しい状況にも対処する必要があります。

于 2012-07-19T12:20:25.530 に答える