排序NSD的NSArray

Jon*_*an. 11 cocoa nsdate nsarray

我有一个NSAd的NSDate对象,我想对它们进行排序,以便今天是0,昨天是1等.

它是升序还是降序,我使用函数,选择器还是什么?

Fir*_*eer 38

NSArray有不同的排序方法,因为您可能有不同的排序方式.NSSortDescriptors是一种通用的方法,可以为您提供很多选项,包括在排序中使用哪些键,要在这些键上使用哪些选择器,以及要使用的总体顺序等.或者您可以使用函数或比较器块来代替您的情况需要或者如果您的特定情况更方便.

要回答你的第一个问题,如果你想今天成为第一个问题,然后是昨天,那么,是的,这当然是降序.

要按降序排序某些日期,您可以这样做:(假设NSArray充满了名为'dateArray'的NSDate):

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];
[descriptor release];

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];
Run Code Online (Sandbox Code Playgroud)

或者,如果您正在为iOS 4+或Snow Leopard +构建,则可以执行以下操作:

NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator: 
                                       ^(id obj1, id obj2) {
                                           return [obj2 compare:obj1]; // note reversed comparison here
                                       }];
Run Code Online (Sandbox Code Playgroud)