for Objective-C 中用于访问 NSMutable 字典的每个循环
我发现在 Objective-C 中访问可变字典键和值时有些困难。
假设我有这个:
NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];
我可以设置键和值。现在,我只想访问每个键和值,但我不知道设置的键的数量。
在 PHP 中这非常简单,如下所示:
foreach ($xyz as $key => $value)
在 Objective-C 中怎么可能?
I am finding some difficulty in accessing mutable dictionary keys and values in Objective-C.
Suppose I have this:
NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];
I can set keys and values. Now, I just want to access each key and value, but I don't know the number of keys set.
In PHP it is very easy, something as follows:
foreach ($xyz as $key => $value)
How is it possible in Objective-C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这适用于符合 NSFastEnumeration 协议(在 10.5+ 和 iOS 上可用)的每个类,尽管 NSDictionary 是少数几个允许您枚举键而不是值的集合之一。我建议您阅读快速枚举 在集合编程主题中。
哦,我应该补充一点,在枚举集合时,您不应该永远修改集合。
This works for every class that conforms to the NSFastEnumeration protocol (available on 10.5+ and iOS), though
NSDictionary
is one of the few collections which lets you enumerate keys instead of values. I suggest you read about fast enumeration in the Collections Programming Topic.Oh, I should add however that you should NEVER modify a collection while enumerating through it.
只是为了不要遗漏使用块枚举键和值的 10.6+ 选项...
如果您希望操作同时发生:
Just to not leave out the 10.6+ option for enumerating keys and values using blocks...
If you want the actions to happen concurrently:
如果您需要在枚举时变异字典:
If you need to mutate the dictionary while enumerating:
枚举字典的最简单方法是
其中
tDictionary
是您要迭代的NSDictionary
或NSMutableDictionary
。The easiest way to enumerate a dictionary is
where
tDictionary
is theNSDictionary
orNSMutableDictionary
you want to iterate.我建议您阅读 枚举:遍历集合编程指南中的集合元素部分对于可可。有一个示例代码可以满足您的需要。
I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.
10.5 和 iPhone OS 中添加了快速枚举,而且速度明显更快,而不仅仅是语法糖。如果您必须以较旧的运行时为目标(即 10.4 及向后版本),则必须使用旧的枚举方法:
您不释放枚举器对象,并且无法重置它。如果你想重新开始,你必须从字典中请求一个新的枚举器对象。
Fast enumeration was added in 10.5 and in the iPhone OS, and it's significantly faster, not just syntactic sugar. If you have to target the older runtime (i.e. 10.4 and backwards), you'll have to use the old method of enumerating:
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.
您可以使用
-[NSDictionary allKeys]
访问所有键并循环遍历它。You can use
-[NSDictionary allKeys]
to access all the keys and loop through it.