【问题标题】:Unable to sort an Array of integers?无法对整数数组进行排序?
【发布时间】:2012-04-27 07:33:55
【问题描述】:

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

这是我的数组:

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
)

它会先排序四位数字,然后是三位数字。

【问题讨论】:

  • sortedArray2的顺序有什么问题?您正在记录按字符串值排序的 keyArray,而 sortedArray2 应该按整数值正确排序...?

标签: iphone objective-c


【解决方案1】:

你可以很容易地实现你想要的,试试这个:

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

【讨论】:

    【解决方案2】:
    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...

    希望对你有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 2013-09-06
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多