Sort NSArray by int contained in array

I have an array, let it be called an "array", and inside the array I have such objects:

"0 Here is the object"

"4 Here is another object"

"2 Let here too!"

"1 What the hell is different here!"

"3 Let it be right here."

I would like to sort arrays by this number, so it will turn into this:

"0 Here is the object"

"1 What the hell is different here!"

"2 Let here too!"

"3 Let it be right here."

"4 Here is another object"

+3
source share
2 answers

You can use the NSArray's sortedArrayUsingFunction: Context: method to sort them. This method uses a function that can be used to compare two elements in an 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 another object",
                      @"25 Let put 2 here too!",
                      @"1 What the heck, here another!",
                      @"3 Let put this one right here",
                      nil];

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

    [pool drain];
    return 0;
}
+8

sortedArrayUsingFunction: sortedArrayUsingComparator: , compare:options: , NSNumericSearch.

+1

Source: https://habr.com/ru/post/1725105/


All Articles