如何在ios中降序排序数组?

时间:2015-12-11 09:28:36

标签: ios objective-c arrays sorting

我有一个数组如何在降序中对此进行排序 下面是我需要排序的数组我该怎么做?以下是我写的代码

array(
"4.3",
"4.8",
"4.4",
"4.8",
"6.5"
) 


  NSSortDescriptor *sortDescriptor;
  sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"floats" ascending:YES];
  NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
  [sortArray sortUsingDescriptors:sortDescriptors];
  NSLog(@"sort array %@",sortArray);

3 个答案:

答案 0 :(得分:2)

试试以下代码。

NSArray *arForData = @[@4.3,@4.8,@4.4,@4.8,@6.5];
NSArray *sortedArray = [arForData  sortedArrayUsingComparator:
                            ^NSComparisonResult(id obj1, id obj2){
                                //descending order
                                return [obj2 compare:obj1];
                                //ascending order
                                return [obj1 compare:obj2];
                            }];
NSLog(@"%@",sortedArray);

结果 - 降序 (     " 6.5&#34 ;,     " 4.8&#34 ;,     " 4.8&#34 ;,     " 4.4&#34 ;,     " 4.3" )

结果 - 升序 (     " 4.3&#34 ;,     " 4.4&#34 ;,     " 4.8&#34 ;,     " 4.8&#34 ;,     " 6.5" )

答案 1 :(得分:1)

只需将NO传递给ascending参数:

sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"floats" ascending:NO];

答案 2 :(得分:-1)

NSArray *arr = [NSArray arrayWithObjects:@4.3,@4.8,@4.4,@4.8,@6.5,nil];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"floats" ascending:NO];
NSMutableArray *sortArray = [NSMutableArray arrayWithObject:arr];
[sortArray sortUsingDescriptors:@[sortDescriptor]];
NSLog(@"sort array %@",sortArray);