我有一个像:
这样的数组( “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];
但没有获得正确的排序数组。
答案 0 :(得分: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"
)
答案 1 :(得分:2)
要按降序顺序排序,您只需在代码中切换firstObject和secondObject:
sortedArray = [arr_distance sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [((NSString *)secondObject) compare:((NSString *)firstObject) options:NSNumericSearch];
}];
答案 2 :(得分: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);
答案 3 :(得分: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