anotherCoder
anotherCoder

Reputation: 732

traversing dictionary in key order

I am using the following syntax to print the dictionary:

for(id key in myDict)
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

But I notice that, the oeder is not according to index. Say for eg. if my dictionary is

myDict = { 1:a, 2:b, 3:c....26:z}

The above code won't print the value in oreder 1,2,3,4 but in a random order.

How do I get to traverse that dictionary in order using enumeration code, like the one specified above. The key in my usage is a string such as "ajay" " abhi: etc

EDIT : Is copying keys into another array inevitable?? is that the only way.

Upvotes: 0

Views: 170

Answers (5)

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

How do I get to traverse that dictionary in order using enumeration code, like the one specified above. The key in my usage is a string such as "ajay" " abhi: etc

As per your setObject in NSDictionary, you don't retrieve in that order.

If you want to get the result in any sorted order other than your adding order.

Then you can get all the keys as array [dict allKeys] and then sort this array and then retrive the Object from the dictionary.

NSMutableDictionary *dict=[NSMutableDictionary new];
[dict setObject:@"anoop" forKey:@"aKey"];
[dict setObject:@"john" forKey:@"jKey"];
[dict setObject:@"baban" forKey:@"bKey"];
[dict setObject:@"chandan" forKey:@"cKey"];

NSArray *keys=[dict allKeys];
NSArray *sortedKeys=[keys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *key in sortedKeys) {
    NSLog(@"Key: %@, Value : %@",key,dict[key]);
}

Upvotes: 2

Hermann Klecker
Hermann Klecker

Reputation: 14068

As per definition a dictionary is not orderd. You cannot even assume that the existing order stays the same.

You could fetch the allKeys array from the dictionary, sort it and then access the values for the keys by iterating through the sorted array.

Upvotes: 1

Jerome Diaz
Jerome Diaz

Reputation: 1866

retrieve your dictionary keys in an array

sort this key array

use this array to retrieve your dictionary values

Upvotes: 1

Fogmeister
Fogmeister

Reputation: 77631

You can get the keys like so...

NSArray *keys = [myDict allKeys];

Then sort the keys and iterate the sorted keys array to get the values in order.

Upvotes: 1

Wevah
Wevah

Reputation: 28242

If you need items to be in a particular order, you should be using an NSArray. Dictionary keys' order is not guaranteed.

Upvotes: 1

Related Questions