按降序排序数组(NSArray)

Gir*_*ari 21 cocoa objective-c

我有一个NSString对象数组,我必须通过降序排序.

由于我没有找到任何API来按降序对数组进行排序,我通过以下方式接近.

我为下面列出的NSString写了一个类别.

- (NSComparisonResult)CompareDescending:(NSString *)aString
{

    NSComparisonResult returnResult = NSOrderedSame;

    returnResult = [self compare:aString];

    if(NSOrderedAscending == returnResult)
        returnResult = NSOrderedDescending;
    else if(NSOrderedDescending == returnResult)
        returnResult = NSOrderedAscending;

    return returnResult;
}
Run Code Online (Sandbox Code Playgroud)

然后我使用语句对数组进行了排序

NSArray *sortedArray = [inFileTypes sortedArrayUsingSelector:@selector(CompareDescending:)];
Run Code Online (Sandbox Code Playgroud)

这是正确的解决方案?有更好的解决方案吗?

小智 54

您可以使用NSSortDescriptor:

NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)];
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:@[sortDescriptor]];
Run Code Online (Sandbox Code Playgroud)

这里我们localizedCompare:用来比较字符串,并传递NO给ascending:选项以降序排序.


小智 6

或简化您的解决方案:

NSArray *temp = [[NSArray alloc] initWithObjects:@"b", @"c", @"5", @"d", @"85", nil];
NSArray *sortedArray = [temp  sortedArrayUsingComparator:
                        ^NSComparisonResult(id obj1, id obj2){
                            //descending order
                            return [obj2 compare:obj1]; 
                            //ascending order
                            return [obj1 compare:obj2];
                        }];
NSLog(@"%@", sortedArray);
Run Code Online (Sandbox Code Playgroud)


ank*_*dav 5

NSSortDescriptor *sortDescriptor; 
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[wordsArray sortUsingDescriptors:sortDescriptors];
Run Code Online (Sandbox Code Playgroud)

使用此代码,我们可以根据长度以降序对数组进行排序。