问题描述
我知道 NSDictionaries
,你需要一个键
来得到一个值
。但是我怎样才能迭代 NSDictionary 键
和值
c>,以便我知道哪些键,哪些是什么值?我知道在 JavaScript
中有一个叫做 for-in-loop 的东西。是否有类似于 Objective-C
?
I know NSDictionaries
as something where you need a key
in order to get a value
. But how can I iterate over all keys
and values
in a NSDictionary
, so that I know what keys there are, and what values there are? I know there is something called a for-in-loop in JavaScript
. Is there something similar in Objective-C
?
推荐答案
code> NSDictionary 支持快速枚举。使用Objective-C 2.0,您可以这样做:
Yes, NSDictionary
supports fast enumeration. With Objective-C 2.0, you can do this:
// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
另一种方法(如果您的目标是Mac OS X 10.5之前的版本,但你仍然可以在10.5和iPhone上使用)是使用 NSEnumerator
:
The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator
:
NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
这篇关于有没有办法迭代字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!