user2893370
user2893370

Reputation: 711

Sort NSDictionary as per date-wise in iphone

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];
}];

Upvotes: 0

Views: 493

Answers (3)

Divya Bhaloidiya
Divya Bhaloidiya

Reputation: 5064

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);

Upvotes: 2

Rajath Shetty K
Rajath Shetty K

Reputation: 424

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];
}];

Upvotes: 0

kirti Chavda
kirti Chavda

Reputation: 3015

try this code:

NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:@selector(compare:)];

Upvotes: 1

Related Questions