问题
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