How to sort NSMutableArray of date objects

Joker picture Joker · Dec 2, 2012 · Viewed 12.3k times · Source

I'm doing some small work on sorting the date strings in the NSMutableArray, i'm getting the array from the sqlite db. If you print the array it is showing like this

date strings are ( "2011-05-01", "2011-02-01", "2012-01-08", "2012-05-08", "2010-01-09 )

I want to show the dates in ascending order. Please help me out guys..... I'm newbie to objc..

Answer

Anoop Vaidya picture Anoop Vaidya · Dec 2, 2012

First you should convert all date Strings (which is NSString) objects to NSDate objects and then sort these dateObjects.

I believe you have dateArray containing all those strings.

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" 
                                                           ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject:descriptor];
NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

OR

NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator: 
                                       ^(id obj1, id obj2) {
                                           return [obj2 compare:obj1];
                                       }];