1

我有一个像这样的数组:

( "8461.86","8468.22","8468.22","8162.59","8164.50","7280.59" )

我尝试按以下顺序对这个数组进行排序:

sortedArray = [arr_distance sortedArrayUsingComparator:^(id firstObject, id secondObject) {
    return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];

但我得到了以下数组:

( "7280.59","8162.59","8164.50","8461.86","8468.22","8468.22" )

为什么会这样?

我也尝试喜欢

return [firstObject compare:secondObject options:NSNumericSearch];

但没有得到正确的排序数组。

4

4 回答 4

2
NSSortDescriptor *desc = [[NSSortDescriptor alloc]initWithKey:@"" ascending:NO];
NSMutableArray *yourTempArray = [[NSMutableArray alloc]initWithObjects:@"8459.93",@"8466.28",@"8466.28",@"8160.70",@"8162.61",@"7278.56", nil];
[yourTempArray sortUsingDescriptors:[NSArray arrayWithObject:desc]];
NSLog(@"sotedAr == %@",yourTempArray);

输出:

sotedAr == (
"8466.28",
"8466.28",
"8459.93",
"8162.61",
"8160.70",
"7278.56"

)

于 2013-04-16T06:31:53.103 回答
2

要按降序排序,您只需在代码中切换 firstObject 和 secondObject:

sortedArray = [arr_distance sortedArrayUsingComparator:^(id firstObject, id secondObject) {
  return [((NSString *)secondObject) compare:((NSString *)firstObject) options:NSNumericSearch];
}];
于 2013-04-16T06:36:36.540 回答
1

下面的代码可能对按降序对数组进行排序很有用

NSArray *arr = [NSArray arrayWithObjects:@"8459.93",@"8466.28",@"8466.28",@"8160.70",@"8162.61",@"7278.56", nil];
NSMutableArray *yourTempArray = [[NSMutableArray alloc]init];
[yourTempArray addObjectsFromArray:arr];
NSLog(@"before sorting = %@",yourTempArray);
NSSortDescriptor* sort = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO];

[yourTempArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
NSLog(@"After sorting = %@",yourTempArray);
于 2013-04-16T06:29:01.207 回答
1

尝试以下代码: -

NSSortDescriptor *frequencyDescriptor = [NSSortDescriptor sortDescriptorWithKey:@""
                                                               ascending:NO
                                                              comparator:^(id obj1, id obj2) {
                                                                  return [obj1 compare:obj2 options:NSNumericSearch];
                                                              }];
NSEnumerator * enumerator = [arr_distance objectEnumerator];
NSArray * descriptors = [NSArray arrayWithObjects:frequencyDescriptor, nil];
NSArray * sortedArray =   [arr_distance sortedArrayUsingDescriptors:descriptors];
enumerator = [sortedArray objectEnumerator];
NSLog(@"sortedArray = %@",sortedArray);

// 使用 sortedArray 进行排序

于 2013-04-16T06:41:23.353 回答