Friday, December 30, 2016

Objective C Sorting NSDictionary based on Values

We often need to sort the key value pairs based on the value and have the keys to run the show. In this post let’s discuss Dictionary sorting based on values.

  
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:2500], @"AAAA",
                                              [NSNumber numberWithInt:3200], @"BBBB",
                                              [NSNumber numberWithInt:2800], @"CCCC",
                                              [NSNumber numberWithInt:1200], @"DDDD",                                                                                                        nil];


I have taken a dictionary which is having key value pairs. The values are numbers. I need to sort(Ascending / Descending) those values and have the sorted keys ready.

The sorting could be Ascending or Descending. So let me take a function and pass my sorting type as shown below.

  
  - (void)sortDict:(BOOL)isAscending {
    
      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:2500], @"AAAA",
                                              [NSNumber numberWithInt:3200], @"BBBB",
                                              [NSNumber numberWithInt:2800], @"CCCC",
                                              [NSNumber numberWithInt:1200], @"DDDD",
                                                                                                        nil];
    
      NSArray *sortedKeys = [dict keysSortedByValueUsingComparator: 
                                                                             ^(id obj1, id obj2) {
            if(isAscending){
               return [obj1 compare:obj2];
            }
            else {
                return [obj2 compare:obj1];
            }

       }];
    
      NSLog(@"Sorted Keys: %@",sortedKeys.description);    

  }


Technically we can use keysSortedByValueUsingComparator method of NSDictionary to do this and based on the sorting type passed we need to change the comparison in the block.

  
       if (isAscending) {
           return [obj1 compare:obj2];
       }

       else {
           return [obj2 compare:obj1];
       }



  
 Ascending :

     Sorted Keys: (
     BBBB,
     CCCC,
     AAAA,
     DDDD
     )

 Descending :

     Sorted Keys: (
     DDDD,
     AAAA,
     CCCC,
     BBBB

     )


As simple as that. Now you have your Dictionary keys in your sorted order.


Hope this post is useful. Feel free to comment in case of any queries.