ios 循环遍历 NSMutableDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3914369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:53:16  来源:igfitidea点击:

looping through an NSMutableDictionary

objective-ciosnsmutabledictionary

提问by Rupert

How do I loop through all objects in a NSMutableDictionary regardless of the keys?

无论键如何,如何遍历 NSMutableDictionary 中的所有对象?

回答by Henrik P. Hessel

A standard way would look like this

一个标准的方式看起来像这样

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

回答by Andrey Zverev

you can use

您可以使用

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

if your target OS supports blocks.

如果您的目标操作系统支持块。

回答by jv42

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

您可以使用[dict allValues]来获取NSArray您的值。请注意,它不保证调用之间的任何顺序。

回答by user3540599

  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
  1. 对于简单循环,快速枚举比基于块的循环快一点
  2. 使用基于块的枚举进行并发或反向枚举比使用快速枚举更容易使用 NSDictionary 进行循环时,您可以使用基于块的枚举器一次性获得键和值,而使用快速枚举则必须使用键来检索单独消息发送中的值

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
  }];

回答by Alexander

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

您不需要为变量赋值。您可以直接使用myDict[key].

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

回答by Hendrik

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

另一种方法是使用 Dicts Enumerator。以下是来自 Apple 的一些示例代码:

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

while ((value = [enumerator nextObject])) {
    /* code that acts on the dictionary's values */
}