0

I have NSMutableDictionary with Integers as Key and NSString as Values for example:

Key -- Value

1 -- B

2 -- C

3 -- A

Now i want to Sort NSMutableDictionary alphabetically using values. So i want my dictionary to be like : Key(3,1,2)->Value(A,B,C). How can i perform this?

Shaunak
  • 707
  • 1
  • 9
  • 29

2 Answers2

3

From Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html#//apple_ref/doc/uid/20000134-SW4

Sorting dictionary keys by value:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:63], @"Mathematics",
    [NSNumber numberWithInt:72], @"English",
    [NSNumber numberWithInt:55], @"History",
    [NSNumber numberWithInt:49], @"Geography",
    nil];

NSArray *sortedKeysArray =
    [dict keysSortedByValueUsingSelector:@selector(compare:)];
// sortedKeysArray contains: Geography, History, Mathematics, English

Blocks ease custom sorting of dictionaries:

NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

     if ([obj1 integerValue] > [obj2 integerValue]) {
          return (NSComparisonResult)NSOrderedDescending;
     }

     if ([obj1 integerValue] < [obj2 integerValue]) {
          return (NSComparisonResult)NSOrderedAscending;
     }
     return (NSComparisonResult)NSOrderedSame;
}];
Ajith Renjala
  • 4,934
  • 5
  • 34
  • 42
  • Quite interesting, I guess the only meaningful way to store the 'sorted' dictionary is storing in an array, as dictionaries by their very nature have no order, right? – Woodstock Mar 24 '14 at 07:27
  • 1
    @JohnWoods - Correct, an `NSDictionary` is an unordered collection of key. value pairs. – CRD Mar 24 '14 at 07:45
  • Yes, NSDictionary is hash table based. When you say, 'sorted' dictionary, it's the 'keys' which you need in order to get their values. – Ajith Renjala Mar 24 '14 at 07:53
2

try this logic

  NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"B",@"B",@"A",@"A",@"C",@"C", nil];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:[dict allKeys]];
    [sortedArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for (NSString *key in sortedArray) {
        NSLog(@"%@",[dict objectForKey:key]);
    }
Rajesh
  • 10,318
  • 16
  • 44
  • 64