views:

104

answers:

2

I'm trying to make a high score table, and suck at arrays in objective c (actually, in general objective c is challenging for me), so I can't figure out how to sort. I'm trying to do something like this (speudocode, I'm writing this in actionscript style because I'm more comfortable with it):

highscores.addObjecttoArray(score)
highscores.sort(ascending)

But I can't figure it out... I've seen other threads about it, but their use plist files and stuff and I don't know enough objective c to learn from them.

+9  A: 

[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:)];

Wevah
I'll giv this a try, thanks.
meman32
Ok, minor problem, I think thats sorting it the wrong way... Is their anyway to switch that around?
meman32
you mean ascending and descending?
vodkhang
You said ascending in the question, but I'll edit it with extra info. :)
Wevah
I always get ascending and descending mixed up, thanks for the help.
meman32
(Don't forget to accept the answer if it answers your question! ;) )
Wevah
@Wevah, while it is very educational to use categories or blocks, there are sorting mechanisms (`NSSortDescriptor`) for simple ordering like this case.
ohhorob
That is true. (+1)
Wevah
+5  A: 

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.

ohhorob