ios - 如何按日期降序对 NSDate 进行排序,但在该日期内时间升序?
<p><p>我使用 NSFetchedResultsController 和 NSSortDescriptor 成功排序到一个表格中,每个日期都有一个部分,因此今天的日期首先出现(日期降序)。</p>
<p>但是,在该部分中,我希望按升序对时间进行排序。</p>
<p>这是我当前的代码,没有按时间排序:</p>
<pre><code>//Set up the fetched results controller.
NSFetchRequest *fetchRequest = [ init];
NSEntityDescription *entity = ;
fetchRequest.entity = entity;
// Sort using the timeStamp property..
NSSortDescriptor *sortDescriptor = [ initWithKey:@"date" ascending:NO];
NSArray *sortDescriptors = [ 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 = [ initWithFetchRequest:fetchRequest managedObjectContext:global.managedObjectContext sectionNameKeyPath:sortPath cacheName:nil];
fetchedResultsController.delegate = self;
</code></pre>
<p>请问如何更改代码以在此日期部分中按时间升序添加排序?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我认为您需要一个特殊的比较器。使用<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html#//apple_ref/occ/instm/NSSortDescriptor/initWithKey%3aascending%3acomparator%3a" rel="noreferrer noopener nofollow">initWithKey:ascending:comparator:</a>初始化您的排序描述符并作为比较器传递:</p>
<pre><code>^(id obj1, id obj2) {
NSDateComponents *components1 = [ components:NSHourCalendarUnit|NSDayCalendarUnit fromDate:obj1];
NSInteger day1 = ;
NSInteger hour1 = ;
NSDateComponents *components2 = [ components:NSHourCalendarUnit|NSDayCalendarUnit fromDate:obj2];
NSInteger day2 = ;
NSInteger hour2 = ;
NSComparisonResult res;
if (day1>day2) {
res = NSOrderedAscending;
} else if (day1<day2) {
res = NSOrderedDescending;
} else {
if (hour1>hour2) {
res = NSOrderedDescending;
} else {
res = NSOrderedAscending;
}
}
return res;
}
</code></pre>
<p>这应该让您了解如何实现这一点,您将需要添加分钟和秒组件,并处理小时、分钟和秒相等的情况。</p></p>
<p style="font-size: 20px;">关于ios - 如何按日期降序对 NSDate 进行排序,但在该日期内时间升序?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/11555912/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/11555912/
</a>
</p>
页:
[1]