views:

816

answers:

2

I have an array, let's call it "array" and inside of the array I have objects like this:

"0 Here is an object"

"4 Here's another object"

"2 Let's put 2 here too!"

"1 What the heck, here's another!"

"3 Let's put this one right here"

I would like to sort the arrays by that number, so it'll turn into this:

"0 Here is an object"

"1 What the heck, here's another!"

"2 Let's put 2 here too!"

"3 Let's put this one right here"

"4 Here's another object"

+5  A: 

You can use NSArray's sortedArrayUsingFunction:Context: method to sort these for you. This method takes a function that can be used to compare two items in the array.

#import <Foundation/Foundation.h>

NSInteger firstNumSort(id str1, id str2, void *context) {
    int num1 = [str1 integerValue];
    int num2 = [str2 integerValue];

    if (num1 < num2)
        return NSOrderedAscending;
    else if (num1 > num2)
        return NSOrderedDescending;

    return NSOrderedSame;
}

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSArray *array = [NSArray arrayWithObjects:@"0 Here is an object",
                      @"4 Here's another object",
                      @"25 Let's put 2 here too!",
                      @"1 What the heck, here's another!",
                      @"3 Let's put this one right here",
                      nil];

    NSLog(@"Sorted: %@", [array sortedArrayUsingFunction:firstNumSort context:NULL]);

    [pool drain];
    return 0;
}
Jarret Hardie
Rather than getting a C string and scanning it, you can just do `[string integerValue]` and it will look for a number at the beginning of the string.
Chuck
Thank you Chuck... I knew there had to be a better way. I admit I've never read the docs for integerValue and had no idea that it would be happy with a digit-started string that contained other values. Makes sense though.
Jarret Hardie
Thank you so much!!!!! It works perfectly!!!
Matt S.
+1  A: 

Use sortedArrayUsingFunction: or sortedArrayUsingComparator:, and pass a function or block that sends compare:options: to one of the strings, using the NSNumericSearch option.

Peter Hosey
could you please give me an example
Matt S.
Example of a comparison function: `NSComparisonResult everythingComparesEqual(id a, id b, void *context) { return NSOrderedSame; }`
Peter Hosey
Example of a comparison block: `NSComparator everythingComparesEqual = ^(id a, id b, void *context){ return NSOrderedSame; }`
Peter Hosey
I will leave it to you to replace the contents of one of those with code that sends a `compare:options:` message to the `a` object, passing `b` as the object to compare and `NSNumericSearch` as the option.
Peter Hosey