如何按降序对日期数组进行排序

bas*_*ste 15 objective-c nsdictionary nsdate uitableview ios

我有一个解析为数组的NSDictionary,其中一个元素是date,我尝试使用[startimeArray sortUsingSelector:@selector(compare:)];(starttimeArray)是我的日期,但它只安排升序.我怎样才能按降序排序.谢谢

Ano*_*dya 38

通过将NO设置为升序参数对数组进行排序:

NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];
Run Code Online (Sandbox Code Playgroud)


Vik*_*ica 19

您可以使用比较器块

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
    return [d1 compare:d2];
}];
Run Code Online (Sandbox Code Playgroud)

要扭转订单,只需交换日期

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
    return [d2 compare:d1];
}];
Run Code Online (Sandbox Code Playgroud)

或 - 作为compare:返回NSComparisonResult,实际上是typedef'ed整数,见下文 - 只需乘以-1

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
    return -1* [d1 compare:d2];
}];
Run Code Online (Sandbox Code Playgroud)
enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
Run Code Online (Sandbox Code Playgroud)

  • 我建议,为了便于阅读,该块更明确.也许检查它是否是"NSOrderedAscending"并明确设置为"NSOrderedDescending",反之亦然.这两种方法(切换参数顺序并乘以-1)对我的影响很大,因为它过分依赖于实现细节而未被未来读者清楚. (2认同)