배열에 포함 된 int별로 nsarray를 정렬
문제
배열이 있습니다. "배열"이라고 부르고 배열 안에는 다음과 같은 객체가 있습니다.
"0 여기에 개체가 있습니다"
"4 여기 다른 대상이 있습니다"
"2 여기에 2를 넣자!"
"1 도대체 또 다른데!"
"3 바로 여기에 넣자"
배열을 해당 숫자로 정렬하고 싶습니다.
"0 여기에 개체가 있습니다"
"1 도대체 또 다른데!"
"2 여기에 2를 넣자!"
"3 바로 여기에 넣자"
"4 여기 다른 대상이 있습니다"
해결책
당신이 사용할 수있는 NSArray's
SortedArrayusingFunction : 컨텍스트 : 당신을 위해 이것들을 정렬하는 방법. 이 방법은 배열의 두 항목을 비교하는 데 사용할 수있는 함수를 사용합니다.
#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;
}
다른 팁
사용 sortedArrayUsingFunction:
또는 sortedArrayUsingComparator:
, 보내는 함수 또는 블록을 전달합니다 compare:options:
줄을 사용하여 NSNumericSearch
옵션.
제휴하지 않습니다 StackOverflow