gpt4 book ai didi

ios - 如何按日期降序对 NSDate 进行排序,但在该日期内时间升序?

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:14:38 24 4
gpt4 key购买 nike

我使用 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;

请问如何更改代码以在此日期部分添加按时间升序排序?

最佳答案

我认为你需要一个特殊的比较器。使用 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;
}

这应该让您了解如何实现这一目标,您将需要添加分和秒组件,并处理时、分和秒相等的情况。

关于ios - 如何按日期降序对 NSDate 进行排序,但在该日期内时间升序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com