I have an NSArray
of NSNumber
objects that I have successfully sorted in ascending order using the following:
[myArray sortedArrayU
If you need based on ABCD in ascending then use following code
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[yourArray sortedArrayUsingDescriptors:descriptors];
use sortarrayusingcomparator method like that
NSArray *sortedArray = [array sortedArrayUsingComparator:
^NSComparisonResult(id obj1, id obj2){
return [obj2 compare:obj1];
}];
by reversing the order of objects you will obtain a descending order
There are a few ways:
sortUsingFunction:context:
.sortUsingComparator:
, which takes a block. (Only available in Mac OS X 10.6 and later and iOS 4.0 and later.)sortUsingDescriptors:
, and pass an array of at least one sort descriptor whose ascending
property is false.In the first two cases, your comparison should simply return the negation of what the comparator you normally use (e.g., compare:
) returned. The last one involves less custom code, so it's what I'd use.
Use a sort descriptor
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self"
ascending: NO];
return [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
comare selector has to return NSComparisonResult. It's actually your function, so you can write another function, that returns the opposite result to sort in descending order.
Use the following code to sort Array on the basis of key on which you want to sort tge array (e.g name , code, address,emp_id etc...)
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Enter Sort Type" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
return [array sortedArrayUsingDescriptors:sortDescriptors];