-1

I had a array how to sort this in descending oder below is the array I need to sort How can I do this ? and below is the code I written

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);
user5276912
  • 131
  • 1
  • 1
  • 8
  • You need to convert float to NSNumbe first. then you can apply compare with sortedArrayUsingComparator.[Reference](http://stackoverflow.com/questions/7610379/how-to-sort-an-nsarray-of-float-values) – Pawan Rai Dec 11 '15 at 09:31

3 Answers3

2

Just try below code.

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

Result- descending ( "6.5", "4.8", "4.8", "4.4", "4.3" )

Result- ascending ( "4.3", "4.4", "4.8", "4.8", "6.5" )

Nimit Parekh
  • 16,776
  • 8
  • 50
  • 72
  • sortedArrayUsingComparator is the absolutely most flexible and at the same time most efficient way to sort arrays. Since you write the code, it can sort in _any_ way you like. – gnasher729 Dec 11 '15 at 09:43
1

Just pass NO to ascending parameter:

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

Michał Ciuba
  • 7,876
  • 2
  • 33
  • 59
-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);
vaibby
  • 1,255
  • 1
  • 9
  • 23