Slavcho
Slavcho

Reputation: 2812

Sort NSDictionary keys according to NSArray elements

I have NSDictionary filled with many objects. I have sorted the keys in a desired pattern and now I have the keys only in a new NSArray. How to apply the changes so the order of the elements in the array to be reflected in the dictionary?
For ex. NSArray -> ["D" , "B" , "A" , "C"] this order I want to apply to the keys in the dictionary.

NSDictionary -> {{"A" : <something>} , {"B" : <something>} , {"C" : <something>} , {"D" : <something>}}

Upvotes: 0

Views: 81

Answers (1)

greg
greg

Reputation: 2006

You don't. You iterate over the keys in the array and then pull out the data from the dictionary.

for (NSString *key in sortedKeys) {
    id value = dictionary[key];
    // do something...
}

If you need ordering you might consider using NSOrderedSet or rolling your own data structure to do this. For example, I have created data structures that use both NSIndexSet and NSDictionary to provide key/value storage with faster sorted enumeration.

Upvotes: 2

Related Questions