Sorting array(NSArray) in descending order

Viewed 34788

I have a array of NSString objects which I have to sort by descending.

Since I did not find any API to sort the array in descending order I approached by following way.

I wrote a category for NSString as listed bellow.

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

    NSComparisonResult returnResult = NSOrderedSame;

    returnResult = [self compare:aString];

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

    return returnResult;
}

Then I sorted the array using the statement

NSArray *sortedArray = [inFileTypes sortedArrayUsingSelector:@selector(CompareDescending:)];

Is this right solution? is there a better solution?

3 Answers

You can use NSSortDescriptor:

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

Here we use localizedCompare: to compare the strings, and pass NO to the ascending: option to sort in descending order.

Related