0

I have a dictionary like:

{
    "2014-04-12" =     (
                {
            "can_remove" = 1;
            "date_created" = "12-04-2014 04:23:57";
            "is_connected" = 0;
            name = "J J";
            status = gbn;
            "user_id" = 94;
        }
    );
    "2014-04-14" =     (
                {
            "can_remove" = 0;
            "date_created" = "14-04-2014 02:36:52";
            "is_connected" = 0;
            name = abc;
            "user_id" = 89;
        }
    );
}

The keys of this dictionary represent dates. How can I sort this by date?

I tried this, but it doesn't work:

NSArray* keys = [dict allKeys];
    NSArray* sortedArray = [keys sortedArrayUsingComparator:^(id a, id b) {
        return [a compare:b options:NSNumericSearch];
}];
rdurand
  • 7,342
  • 3
  • 39
  • 72
user2893370
  • 701
  • 1
  • 9
  • 23

3 Answers3

2

Use following way to sort the dictionary according to date :

NSMutableArray *dictKeys = [[dict allValues] mutableCopy];

[dictKeys sortUsingComparator: (NSComparator)^(NSDictionary *a, NSDictionary *b) 
  {
    NSString *key1 = [a objectForKey: @"field3"];  
    NSString *key2 = [b objectForKey: @"field3"];

    return [key1 compare: key2];
  }
];

NSLog (@"dictKeys - %@",dictKeys);
Bin0li
  • 168
  • 16
Divya Bhaloidiya
  • 5,018
  • 2
  • 25
  • 45
1

try this code:

NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
kirti Chavda
  • 3,029
  • 2
  • 17
  • 29
0

check this code..

// currentDic has all data.

NSArray * tempArray = currentDic.allKeys;

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];

NSArray * sortedArray = [tempArray sortedArrayUsingComparator:^NSComparisonResult(NSString * obj1, NSString * obj2) {
    NSDate * firstDate = [formatter dateFromString:obj1];
    NSDate * secondDate = [formatter dateFromString:obj2];

    return [firstDate compare:secondDate];

}];

if you need it as dictionary then,

  NSMutableDictionary * resultingDic = [NSMutableDictionary dictionary];
  [sortedArray enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL *stop) {

    resultingDic[obj] = currentDic[obj];
}];
Rajath Shetty K
  • 424
  • 3
  • 9