dontWatchMyProfile
dontWatchMyProfile

Reputation: 46310

How to iterate over an dictionary without knowing the keys, while getting key and object?

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?

Upvotes: 5

Views: 3675

Answers (5)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

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!

Upvotes: 0

zekel
zekel

Reputation: 9457

This is also a good choice if you like blocks.

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

}]

Upvotes: 7

sjobe
sjobe

Reputation: 2837

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

Upvotes: 0

fbrereto
fbrereto

Reputation: 35925

I think what you want is something like this:

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

Taken from here.

Upvotes: 8

Colin
Colin

Reputation: 3752

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

Upvotes: 1

Related Questions