Reputation: 566
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
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
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:
Distances
array at the same indices and comparing those.But an array of pairs will be easier...
Upvotes: 1
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