views:

764

answers:

1

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 sorted the array using the statement

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

Is this right solution? is there a better solution?

+5  A: 

You can use NSSortDescriptor:

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

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

Ciarán Walsh
since 'sortDescriptorWithKey' 10.6 aboveI have used following statement.[[NSSortDescriptor alloc] initWithKey: nil ascending: NO];thanks...
Girish Kolari
Indeed, I should have mentioned that – don’t forget the -autorelease though :)
Ciarán Walsh