AaronG
AaronG

Reputation: 522

Sorting NSMutableDictonary on Value AND Key?

I am trying to sort and NSMutableDictionary by value first, then by key. I have the sort by value working with the code below:

       NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
        [dict setObject:[NSNumber numberWithInt:5] forKey:@"eblk"];
        [dict setObject:[NSNumber numberWithInt:2] forKey:@"dstl"];
        [dict setObject:[NSNumber numberWithInt:4] forKey:@"cast"];
        [dict setObject:[NSNumber numberWithInt:4] forKey:@"breb"];
        [dict setObject:[NSNumber numberWithInt:5] forKey:@"apts"];

         NSArray *sortedKeys = [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;
        }];

I then want to sort again based on key so I end up with an array of keys like this:

sortedKeys : corresponding value in dict

"apts": 5

"eblk": 5

"breb": 4

"cast": 4

"dstl": 2

I have the first sort on value working, I'm just not sure how to get started on the secondary sort based on key.

I tried sorting it by key first then by value, but that didn't work.

Any help would be appreciated. Thanks.

Upvotes: 1

Views: 180

Answers (1)

CRD
CRD

Reputation: 53010

What you are trying to do is a two key sort. For any n-key sort you compare the keys in order, returning a result if the current pair are not equal otherwise move onto the next pair of keys and repeat.

Outline sketch for your two keys:

  1. Get an array of the keys so you can sort them
  2. Sort that array using a two key sort:

    • Get the values by looking them up
    • Compare values and return if not equal
    • Compare keys;

Code sketch:

NSArray *allKeys = [dict allKeys];
NSArray *sortedKeys = [allKeys sortedArrayUsingComparator:^(id obj1, id obj2)
{
   NSInteger value1 = [[dict objectForKey:obj1] integerValue];
   NSInteger value2 = [[dict objectForKey:obj2] integerValue];

   if (value1 < value2) 
      return (NSComparisonResult)NSOrderedDescending;
   if (value1 > value2) 
      return (NSComparisonResult)NSOrderedAscending;
   // values are equal, compare keys...         
   return [obj1 compare:obj2];
}];

Upvotes: 3

Related Questions