looping through an NSMutableDictionary

♀尐吖头ヾ 提交于 2019-12-02 14:47:17

A standard way would look like this

for(id key in myDict) {
    id value = [myDict objectForKey:key];
    [value doStuff];
}

you can use

[myDict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
    // do something with key and obj
}];

if your target OS supports blocks.

You can use [dict allValues] to get an NSArray of your values. Be aware that it doesn't guarantee any order between calls.

  1. For simple loop, fast enumeration is a bit faster than block-based loop
  2. It's easier to do concurrent or reverse enumeration with block-based enumeration than with fast enumeration When looping with NSDictionary you can get key and value in one hit with a block-based enumerator, whereas with fast enumeration you have to use the key to retrieve the value in a separate message send

in fast enumeration

for(id key in myDictionary) {
   id value = [myDictionary objectForKey:key];
  // do something with key and obj
}

in Blocks :

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

   // do something with key and obj
  }];

You don't need to assign value to a variable. You can access it directly with myDict[key].

    for(id key in myDict) {
        NSLog(@"Key:%@ Value:%@", key, myDict[key]);
    }

Another way is to use the Dicts Enumerator. Here is some sample code from Apple:

NSEnumerator *enumerator = [myDictionary objectEnumerator];
id value;

while ((value = [enumerator nextObject])) {
    /* code that acts on the dictionary’s values */
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!