Well, first off, you're not actually sorting anything in your code...
You should do something like this...
// create the string array
NSArray *dateArray = @[@"01/12/2012", @"01/26/2011", @"02/09/2005", @"02/24/2006", @"03/19/2007", @"07/14/2011", @"08/17/2007", @"10/04/2007", @"10/31/2006", @"12/05/2012", @"12/06/2006", @"12/23/2008"];
// create the date formatter with the correct format
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy"];
NSMutableArray *tempArray = [NSMutableArray array];
// fast enumeration of the array
for (NSString *dateString in dateArray) {
NSDate *date = [formatter dateFromString:dateString];
[tempArray addObject:date];
}
// sort the array of dates
[tempArray sortUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2) {
// return date2 compare date1 for descending. Or reverse the call for ascending.
return [date2 compare:date1];
}];
NSLog(@"%@", tempArray);
EDIT TO PUT INTO STRING ARRAY
NSMutableArray *correctOrderStringArray = [NSMutableArray array];
for (NSDate *date in tempArray) {
NSString *dateString = [formatter stringFromDate:date];
[correctOrderStringArray addObject:dateString];
}
NSLog(@"%@", correctOrderStringArray);
Also, read up more about NSDate
, NSString
and NSDateFormatter
. Especially how they interact with each other.
NSDate
is a point in time. It does not (and never does) contain any formatting information.
NSDateFormatter
doesn't hold any information about a specific date (i.e. point in time). It is used to take a date and produce a string based on the NSDate
and the format
that you give it.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html