Sort NSArray's by an int contained in the array

偶尔善良 提交于 2019-12-12 16:17:20

问题


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"


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/1870656/sort-nsarrays-by-an-int-contained-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!