Matt S.
Matt S.

Reputation: 13773

Sort NSArray's by an int contained in the array

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"

Upvotes: 3

Views: 3292

Answers (2)

Peter Hosey
Peter Hosey

Reputation: 96363

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

Upvotes: 1

Jarret Hardie
Jarret Hardie

Reputation: 98042

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

Upvotes: 8

Related Questions