如何在不知道键的情况下迭代字典,同时获取键和对象?

发布于 2024-09-06 05:54:49 字数 99 浏览 7 评论 0原文

我有一个 NSDictionary 并想要迭代对象。但同时,我需要知道字典的键。

我记得有一种特殊的、奇特的快速枚举形式,但忘记了确切的语法。

有人吗?

I have an NSDictionary and want to iterate over the objects. But at the same time, I need to know the key of the dictionary.

I remember there was a special, fancy form of fast enumeration, but have forgotten the exact syntax.

Anyone?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

独孤求败 2024-09-13 05:54:49

我认为你想要的是这样的:

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

取自 这里

I think what you want is something like this:

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

Taken from here.

尾戒 2024-09-13 05:54:49

如果你喜欢积木,这也是一个不错的选择。

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

}]

This is also a good choice if you like blocks.

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

}]
栀子花开つ 2024-09-13 05:54:49
for (id key in mydictionary) {
   id mything = [mydictionary objectForKey:key];
}
for (id key in mydictionary) {
   id mything = [mydictionary objectForKey:key];
}
橙味迷妹 2024-09-13 05:54:49

keyEnumerator 返回一个对象,可让您迭代字典中的每个键。来自此处

keyEnumerator returns an object that lets you iterate through each of the keys in the dictionary. From here

安静被遗忘 2024-09-13 05:54:49

据我所知,当您提出问题时,只有一种方法可以同时遍历键和值: CFDictionaryApplyFunction

使用这个 Core Foundation 函数涉及到循环体的丑陋的 C 函数指针和大量同样丑陋但免费的桥接转换。

@zekel 有现代的迭代方式字典。投票给他吧!

To my knowledge, at the time when you asked the question, there was only one way of traversing keys and values at the same time: CFDictionaryApplyFunction.

Using this Core Foundation function involves an ugly C function pointer for the body of the loop and a lot of not-less-ugly, yet toll-free-bridged casting.

@zekel has the modern way of iterating a dictionary. Vote him up!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文