Question

I have an NSDictionary and want to iterate over the objects. But at the same time, I need to know the key of the dictionary.

I remember there was a special, fancy form of fast enumeration, but have forgotten the exact syntax.

Anyone?

Was it helpful?

Solution

I think what you want is something like this:

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

Taken from here.

OTHER TIPS

This is also a good choice if you like blocks.

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

}]
for (id key in mydictionary) {
   id mything = [mydictionary objectForKey:key];
}

keyEnumerator returns an object that lets you iterate through each of the keys in the dictionary. From here

To my knowledge, at the time when you asked the question, there was only one way of traversing keys and values at the same time: CFDictionaryApplyFunction.

Using this Core Foundation function involves an ugly C function pointer for the body of the loop and a lot of not-less-ugly, yet toll-free-bridged casting.

@zekel has the modern way of iterating a dictionary. Vote him up!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top