You can use any of the various sort methods provided by NSArray
and NSMutableArray
. Note, you probably want to convert these dates strings to proper NSDate
objects in case any of them feature different time zones.
For example, you could have a sortedArrayUsingComparator
that used NSDateFormatter
to convert them to dates, and then compare
those:
NSArray *array = @[@{@"date" : @"2015-02-13 12:03:54 CST", @"imgUrl" : @10154469614215076, @"latest" : @"2015-02-13 18:46:42 CST", @"status" : @1, @"userName" : @"Anthony"},
@{@"date" : @"2015-01-13 12:03:54 CST", @"imgUrl" : @10154469614215076, @"latest" : @"2015-01-13 18:46:42 CST", @"status" : @1, @"userName" : @"Dick"},
@{@"date" : @"2015-03-13 12:03:54 CST", @"imgUrl" : @10154469614215076, @"latest" : @"2015-03-13 18:46:42 CST", @"status" : @1, @"userName" : @"Harry"}];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss zzz";
NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate *date1 = [formatter dateFromString:obj1[@"latest"]];
NSDate *date2 = [formatter dateFromString:obj2[@"latest"]];
return [date1 compare:date2];
}];
Or, if it was a NSMutableArray
that you wanted to sort in place, you could do:
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate *date1 = [formatter dateFromString:obj1[@"latest"]];
NSDate *date2 = [formatter dateFromString:obj2[@"latest"]];
return [date1 compare:date2];
}];