无法对整数数组进行排序?

时间:2012-04-27 07:33:55

标签: iphone objective-c

我想按升序对多个数字的整数数组进行排序。

这是我的数组:

keyArray:
(
   978,
   1077,
   1067,
   1076,
   1072,
   1082,
   1079,
   1075,
   1071,
   1081,
   1078,
   1080,
   1074

这是我的代码:

NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"self"  ascending: YES];

NSArray *sortedArray2 = [keyArray sortedArrayUsingComparator:^(id str1, id str2) {

    if ([str1 integerValue] < [str2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }

    if ([str1 integerValue] > [str2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

NSLog(@"%@",[keyArray sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortOrder]]);

问题是这会像这样排序数组

sortedArray: (

  1067,
  1071,
  1072,
  1074,
  1075,
  1076,
  1077,
  1078,
  1079,
  1080,
  1081,
  1082,
  978
)

它将首先对四位数字进行排序,然后对三位数字进行排序。

2 个答案:

答案 0 :(得分:8)

你可以轻松实现自己想要的目标,试试这个:

NSArray * sortedArray2 = [keyArray sortedArrayUsingComparator:^(id str1, id str2){
    return [(NSString *)str1 compare:(NSString *)str2 options:NSNumericSearch];
}];

答案 1 :(得分:0)

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

//想要缩短它时调用它......

NSArray *array = [NSArray arrayWithObjects:@"787",
                  @"344",
                  @"42334",
                  @"23432",
                  @"3423432",
                  nil];

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

For More Visit this reference...

希望,这会对你有帮助......