Hi Forum,
I want to sort an array of NSDate. I have been doing some googling and aside from using descriptors it can be done like this
Code:
sortedArray = [unsortedArray sortedArrayUsingSelector:@selector(compare:)];
now does this sort the array in ascending date or descending date? how would i know?
I always have to puzzle this sort of thing out, or just run a quick test. I'm too tired for either right now. I
think it would sort into smallest-to-largest order, but I'm not positive.
There are about half-a-dozen different ways to sort arrays in Cocoa. sortedArrayUsingSelector is one.
Another useful method is sortedArrayUsingComparator: That method is very powerful, once you get your head around using blocks. For something simple like sorting an array of dates, it's overkill, since sortedArrayUsingSelector works perfectly. If you're sorting something like an array of dictionaries that contain dates, however, sortedArrayUsingComparator makes it pretty easy.
The idea is that you write a block of code that returns an NSComparisonResult value just like the method used in sortedArrayUsingSelector, but the comparator block is a block of code you write rather than a method that has to be defined in the objects you're sorting.
To do the same thing as sortedArrayUsingSelector using a comparator for your array of NSDates, you'd use code like this:
Code:
sortedArray = [datesArray sortedArrayUsingComparator:
^(id obj1, id obj2)
{
return [(NSDate*) obj1 compare: (NSDate*)obj2];
}
];
To reverse the order, you'd just switch the order of the objects in the call to compare:
Code:
sortedArray = [datesArray sortedArrayUsingComparator:
^(id obj1, id obj2)
{
return [(NSDate*) [B]obj2[/B] compare: (NSDate*)[B]obj1[/B]];
}
];