How Do I sort an NSMutable Array with NSNumbers in it? How Do I sort an NSMutable Array with NSNumbers in it? arrays arrays

How Do I sort an NSMutable Array with NSNumbers in it?


Would you like to do that the short way?

If you have a mutable array of NSNumber instances:

NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];[mutableArrayOfNumbers sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];

Nice and easy :)

You can also perform similar sorting with descriptors on immutable arrays, but you will end up with a copy, instead of in-place sorting.


[highscores sortUsingSelector:@selector(compare:)];

Should work if they're definitely all NSNumbers.

(Adding an object is:

[highscores addObject:score];

)

If you want to sort descending (highest-first):

10.6/iOS 4:

[highscores sortUsingComparator:^(id obj1, id obj2) {    if (obj1 > obj2)        return NSOrderedAscending;    else if (obj1 < obj2)        return NSOrderedDescending;    return NSOrderedSame;}];

Otherwise you can define a category method, e.g.:

@interface NSNumber (CustomSorting)- (NSComparisonResult)reverseCompare:(NSNumber *)otherNumber;@end@implementation NSMutableArray (CustomSorting)- (NSComparisonResult)reverseCompare:(NSNumber *)otherNumber {    return [otherNumber compare:self];}@end

And call it:

[highscores sortUsingSelector:@selector(reverseCompare:)];


I tried the answer provided by ohhorob, but the objects were still being sorted alphabetically. Then I ran across this in another answer (https://stackoverflow.com/a/4550451/823356):

I changed my NSSortDescriptor and it now sorts numerically.

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"score"                                               ascending:YES                                              comparator:^(id obj1, id obj2) {    return [obj1 compare:obj2 options:NSNumericSearch];}];

I just thought I'd drop this in here as it solved my 'alphabetical sorting of NSNumbers' problem