I have used NSSortDescriptor to sort my objects using date as key. My code:
NSLog(@"Before sorting: %@", temp);
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"date" ascending: YES];
NSArray *sortedArray2 = [temp sortedArrayUsingDescriptors:[NSArray arrayWithObject: dateSortDescriptor]];
NSLog(@"After sorting: %@", sortedArray2);
NSMutableArray *afterSorting = [[(NSArray*)sortedArray2 mutableCopy]autorelease];
It worked well when the dates are
22/08/2012
23/08/2012
25/09/2012
However, I found that NSSortDescriptor only seemed to sort by the first two numbers in front because when my dates change a little, my result became like this:
10/09/2012
22/08/2012
23/08/2012
Can any one please advice? Saw many other posts using NSSortDescriptor as similar to my codes above but they seem to have no errors any where. For me, it only sort by the day but not the month! What I do is to sort objects with the nearer date on top. Thanks!
The sort ordering you’ve shown is actually correct. The problem is that you’re sorting strings rather than dates. If possible, populate the
dateproperty with instances ofNSDaterather than instances ofNSString, and then the sort will do what you expect.If for some reason you can’t use
NSDateinstances in thedateproperty (which would seem a little odd, but who knows), you can instead sort the array by sending it asortedArrayUsingComparator:message, and passing in a block that defines your custom sort.