Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an NSArray in reverse order

NSArray* sortedArray = [myArray sortedArrayUsingSelector:@selector(compare:)];

Just wondering how I can sort this array of numbers in descending order?

like image 451
Paul Herron Avatar asked Nov 07 '12 16:11

Paul Herron


People also ask

How do you reverse an NSArray in Swift?

In the Swift array, we can reverse the array. To reverse the array we use the reverse() function. This function reverses the order of the specified array. It is the easiest way to reverse the array.

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


2 Answers

Either use the method that allows you to pass a block as a comparator and implement a comparator that reverses the objects (returns NSOrderedAscending for NSOrderedDescending and vice versa)....

... or:

NSArray *reversed = [[[myArray sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];

Sorry. Derped the most important part.

like image 94
bbum Avatar answered Sep 18 '22 15:09

bbum


Use NSSortDescriptor

NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO];
NSArray *temp = [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
like image 28
Midhun MP Avatar answered Sep 19 '22 15:09

Midhun MP