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

StackOverflow https://stackoverflow.com/questions/3064933

  •  28-09-2019
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

I think what you want is something like this:

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

Taken from here.

다른 팁

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!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top