-1

Plz guide me how to sort this dictionary

dict=
{
"april 2012"=[1,2 ,3 ,4],
"march 2013"=[3,4,6,7],
"may 2013"=[6,7,8,3],
"june 2013"=[6,6,7,8,3],

}

how to sort with respect to date from new to old .

Sishu
  • 1,510
  • 1
  • 21
  • 48

1 Answers1

1

Running this code

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@[@6,@6,@7,@8, @3] forKey:@"june 2013"];
[dict setObject:@[@1,@2,@3,@4] forKey:@"april 2012"];
[dict setObject:@[@6,@7,@8,@3] forKey:@"may 2013"];
[dict setObject:@[@3,@4,@6,@7] forKey:@"march 2013"];

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"MMMM yyyy";
NSArray *keys = [dict allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDate *date1 = [dateFormatter dateFromString:obj1];
    NSDate *date2 = [dateFormatter dateFromString:obj2];

    return [date1 compare:date2];
}];

NSLog(@"%@", sortedKeys);

I get

2013-04-28 18:02:10.322 Test[746:19d03] (
    "april 2012",
    "march 2013",
    "may 2013",
    "june 2013"
)

Hope it helps.

EDIT

To get the array in inverse order replace the return with this:

    NSComparisonResult result = [date1 compare:date2];
    if (result == NSOrderedDescending) {
        return NSOrderedAscending;
    } else if (result == NSOrderedAscending) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }

Or you can invert the order of the array (How can I reverse a NSArray in Objective-C?) or just iterate in inverse order

Community
  • 1
  • 1
tkanzakic
  • 5,499
  • 16
  • 34
  • 41