24

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 3

56

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

or simplify your solution:

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);

Comments

6
NSSortDescriptor *sortDescriptor; 
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[wordsArray sortUsingDescriptors:sortDescriptors];

Using this code we can sort the array in descending order on the basis of length.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.