I have a array of NSString objects which I have to sort by descending.
Since I did not find any API to sort the array in descending order I approached by following way.
I wrote a category for NSString as listed bellow.
- (NSComparisonResult)CompareDescending:(NSString *)aString { NSComparisonResult returnResult = NSOrderedSame; returnResult = [self compare:aString]; if(NSOrderedAscending == returnResult) returnResult = NSOrderedDescending; else if(NSOrderedDescending == returnResult) returnResult = NSOrderedAscending; return returnResult; }
Then I sorted the array using the statement
NSArray *sortedArray = [inFileTypes sortedArrayUsingSelector:@selector(CompareDescending:)];
Is this right solution? is there a better solution?
To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.
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...
Use the Reverse() method that would eventually give you a sorted array in descending order. Array. Reverse(list); You can try to run the following code to to sort an array in descending order.
You can reverse a NSArray by writing your own loop iterating from the end towards the beginning and using a second array to add the items in reverse order. Or you can simply use - (NSEnumerator *)reverseObjectEnumerator from the NSArray class.
You can use NSSortDescriptor:
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)]; NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:@[sortDescriptor]];
Here we use localizedCompare:
to compare the strings, and pass NO
to the ascending: option to sort in descending order.
or simplify your solution:
NSArray *temp = [[NSArray alloc] initWithObjects:@"b", @"c", @"5", @"d", @"85", nil]; NSArray *sortedArray = [temp sortedArrayUsingComparator: ^NSComparisonResult(id obj1, id obj2){ //descending order return [obj2 compare:obj1]; //ascending order return [obj1 compare:obj2]; }]; NSLog(@"%@", sortedArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With