macos 如何枚举 CFProperyList / CFDictionary 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2283466/
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
How to enumerate CFProperyList / CFDictionary keys
提问by Till
I would like to iterate through a CFDictionary (CFPropertyList) and get all values on a specific level.
我想遍历 CFDictionary (CFPropertyList) 并获取特定级别的所有值。
This would be my dictionary / property-list:
这将是我的字典/属性列表:
root
A
foo
0
bar
0
B
foo
10
bar
100
C
foo
20
bar
500
Using ObjC it would look something like this:
使用 ObjC,它看起来像这样:
//dict is loaded with the dictionary below "root"
NSDictionary *dict = [...];
NSEnumerator *enumerator = [dict keyEnumerator];
NSString *key;
while (key = [enumerator nextObject])
{
NSLog(key);
};
And it would print out a list of keys to the console like this:
它会像这样打印出控制台的键列表:
A B C
How do you achieve this when using C/C++ on the CoreFoundation-level?
在 CoreFoundation 级别上使用 C/C++ 时如何实现这一点?
回答by kennytm
Use CFDictionaryApplyFunction
to iterate through a dictionary.
使用CFDictionaryApplyFunction
通过字典来迭代。
static void printKeys (const void* key, const void* value, void* context) {
CFShow(key);
}
...
CFDictionaryApplyFunction(dict, printKeys, NULL);
回答by Rob Napier
Based on code from SeeMyFriends:
基于来自SeeMyFriends 的代码:
CFDictionaryRef dict = CFDictionaryCreate(...)
size size = CFDictionaryGetCount(dict);
CFTypeRef *keysTypeRef = (CFTypeRef *) malloc( size * sizeof(CFTypeRef) );
CFDictionaryGetKeysAndValues(dict, (const void **) keysTypeRef, NULL);
const void **keys = (const void **) keysTypeRef;
You can now walk through the pointers in keys[]
. Don't forget to free(keys)
when you're done.
您现在可以浏览 中的指针keys[]
。完成后不要忘记free(keys)
。
Remember that dictionary keys are not strings. They're void*
(which is why they took the trouble of casting keysTypeRef
into keys
). Also note that I've only grabbed keys here, but you could also get values at the same time. See the SeeMyFriends code for a more detailed example.
请记住,字典键不是字符串。他们是void*
(这就是为什么他们不厌其烦地将其转换keysTypeRef
为keys
)。另请注意,我在这里只获取了键,但您也可以同时获取值。有关更详细的示例,请参阅 SeeMyFriends 代码。
回答by hewigovens
CFCopyDescription is helpful when Debugging...
CFCopyDescription 在调试时很有帮助...
CFCopyDescription
Returns a textual description of a Core Foundation object.
CFStringRef CFCopyDescription (
CFTypeRef cf
);