I have a NSDictionary that parsed to an array one of the element is date, i tried using [startimeArray sortUsingSelector:@selector(compare:)];
(starttimeArray) is my date but it only arrange ascending. how can i sort in descending order. thanks
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 ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class.
You can use a comparator block
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
return [d1 compare:d2];
}];
to reverse the order, just swap the dates
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
return [d2 compare:d1];
}];
or — as compare:
returns a NSComparisonResult, which is actually typedef'ed to integer see below — just multiply by -1
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
return -1* [d1 compare:d2];
}];
enum {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
Sort the array by puting NO is ascending parameter:
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];
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