James Anderson
James Anderson

Reputation: 566

Ordering an NSMutableDictionary with multiple keys

I have an NSMutableDictionary with two keys. One for titles (e.g. 'Test') and one for distances (e.g. '200' miles).

How can I order these values by the nearest or furthest distance. I would need both the title AND distance value indexes to change when they are ordered.

So this would be the regular version of the NSMutableDictionary:

Titles: (
    "Test1"
    "Test2"
    "Test3"
)

Distances: (
    "240"
    "43"
    "482"
)

And the ordered version (for nearest distances):

Titles: (
    "Test2"
    "Test1"
    "Test3"
)

Distances: (
    "43"
    "240"
    "482"
)

Upvotes: 1

Views: 644

Answers (3)

Chuck
Chuck

Reputation: 237010

I can't help but feel that what you want is an NSArray of NSDictionaries, or an NSArray of custom objects. This design feels really awkward and creates extra work — because the only real answer if you structure your data this way is "Create a custom API around the whole thing that very carefully manages this invariant, and then only ever mutate this data structure through that interface."

Upvotes: 3

CRD
CRD

Reputation: 53000

As @Chuck says an array of pairs is the obvious structure if sorting these two arrays, or keeping them sorted, is a key operation. If however it is a rare operation and there are very good reasons to keep it as a 2-array dictionary then you can achieve your goal as follows:

  1. Create a new array (NSArray or plain C-array) with the same number, n, of elements as your arrays.
  2. Fill this array with the integers 0 to (n - 1)
  3. Custom sort that array ordering two values based on looking up values in the Distances array at the same indices and comparing those.
  4. When done you have an array of indices being the permutation you wish to apply to your two arrays.
  5. Permute both arrays.

But an array of pairs will be easier...

Upvotes: 1

CSolanaM
CSolanaM

Reputation: 3368

I would do it in this way:

NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"TEST1", @"TITLE", [NSNumber numberWithInt:240], @"DISTANCE", nil];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"TEST2", @"TITLE", [NSNumber numberWithInt:43], @"DISTANCE", nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"TEST3", @"TITLE", [NSNumber numberWithInt:482], @"DISTANCE", nil];

NSSortDescriptor *distanceSort = [NSSortDescriptor sortDescriptorWithKey:@"DISTANCE" ascending:YES]; //Set 'NO' to order from biggest to lowest

NSArray *sortedArrayOfDic = [[NSArray arrayWithObjects:dic1, dic2, dic3, nil] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:distanceSort, nil]];

NSLog(@"%@", sortedArrayOfDict);

The output would be an array of dictionaries sorted by distances, something like:

"43", "TEST2"
"240", "TEST1"
"482", "TEST3"

Upvotes: 0

Related Questions