281

我发现在 Objective-C 中访问可变字典键和值有一些困难。

假设我有这个:

NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];

我可以设置键和值。现在,我只想访问每个键和值,但我不知道设置的键数。

在 PHP 中这很简单,如下所示:

foreach ($xyz as $key => $value)

在 Objective-C 中怎么可能?

4

7 回答 7

683
for (NSString* key in xyz) {
    id value = xyz[key];
    // do stuff
}

这适用于符合 NSFastEnumeration 协议的每个类(在 10.5+ 和 iOS 上可用),但NSDictionary它是少数允许您枚举键而不是值的集合之一。我建议您在Collections Programming Topic中阅读有关快速枚举的内容。

哦,我应该补充一点,你不应该在枚举集合时修改它。

于 2010-01-26T23:06:01.767 回答
101

Just to not leave out the 10.6+ option for enumerating keys and values using blocks...

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
    NSLog(@"%@ = %@", key, object);
}];

If you want the actions to happen concurrently:

[dict enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                              usingBlock:^(id key, id object, BOOL *stop) {
    NSLog(@"%@ = %@", key, object);
}];
于 2010-01-27T05:43:35.067 回答
16

If you need to mutate the dictionary while enumerating:

for (NSString* key in xyz.allKeys) {
    [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}
于 2013-06-03T20:10:00.223 回答
5

我建议您阅读Cocoa 集合编程指南中的枚举:遍历集合元素部分。有一个示例代码可以满足您的需要。

于 2010-01-26T23:05:54.233 回答
5

The easiest way to enumerate a dictionary is

for (NSString *key in tDictionary.keyEnumerator) 
{
    //do something here;
}

where tDictionary is the NSDictionary or NSMutableDictionary you want to iterate.

于 2013-12-17T10:17:01.693 回答
3

快速枚举是在 10.5 和 iPhone OS 中添加的,它的速度明显更快,而不仅仅是语法糖。如果您必须针对较旧的运行时(即 10.4 和向后),则必须使用旧的枚举方法:

NSDictionary *myDict = ... some keys and values ...
NSEnumerator *keyEnum = [myDict keyEnumerator];
id key;

while ((key = [keyEnum nextObject]))
{
    id value = [myDict objectForKey:key];
    ... do work with "value" ...
}

You don't release the enumerator object, and you can't reset it. If you want to start over, you have to ask for a new enumerator object from the dictionary.

于 2010-01-27T00:40:27.043 回答
2

您可以使用-[NSDictionary allKeys]访问所有密钥并循环访问它。

于 2010-01-26T23:07:57.677 回答