OK so I know that dictionaries can't be sorted. But, say I have NSMutableArray *keys = [someDictionary allKeys];
Now, I want to sort those keys, based on the corresponding values in the dictionary (alphabetically). So if the dictionary contains key=someString
, then I want to sort keys
based on the strings they correspond to. I think its some application of sortUsingComparator
but its a little out of my reach at this point.
To correctly sort a dictionary by value with the sorted() method, you will have to do the following: pass the dictionary to the sorted() method as the first value. use the items() method on the dictionary to retrieve its keys and values. write a lambda function to get the values retrieved with the item() method.
You can't sort a Dictionary<TKey, TValue> - it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
NSArray *keys = [someDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [someDictionary objectForKey:a];
NSString *second = [someDictionary objectForKey:b];
return [first compare:second];
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With