-1

I have an a NSMutableArray 'arrcontacts' with the following structure:

{
        date = "2015-02-13 12:03:54 CST";
        imgUrl = 10154469614215076;
        latest = "2015-02-13 18:46:42 CST";
        status = 1;
        userName = Anthony;
}

I would like to take the contents of this array and sort it by the key 'latest', so that the array is ordered with the most recent items first.

What is the best way to do this?

AdamTheRaysFan
  • 175
  • 2
  • 9
  • FWIW, the question that was marked as a duplicate is only half of the solution, because we're dealing with date strings here, not NSDate objects. You want to make sure you convert your objects to proper NSDate objects before availing yourself of any of the options there. – Rob Feb 14 '15 at 21:14

2 Answers2

1

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];
}];
Rob
  • 415,655
  • 72
  • 787
  • 1,044
0

You can use any one of the [-sortedArrayUsing*] methods, such as [arrcontacts sortedArrayUsingFunction:sortByLatest], where sortByLatest is a C Function like this:

NSInteger sortByLatest(NSDictionary* left, NSDictionary* right, void* context)
{
    return [[left objectForKey:@"latest"] compare:[right objectForKey:@"latest"];
}
user1118321
  • 25,567
  • 4
  • 55
  • 86