我有一个CFArrayRef,它主要有CFDictionaryRef,但有时它会包含其他东西。如果可以,我想从数组中的字典中访问一个值,如果不能,我不想崩溃。下面是代码:
bool result = false;
CFArrayRef devices = CFArrayCreateCopy(kCFAllocatorDefault, SDMMobileDevice->deviceList);
if (devices) {
for (uint32_t i = 0; i < CFArrayGetCount(devices); i++) {
CFDictionaryRef device = CFArrayGetValueAtIndex(devices, i);
if (device) { // *** I need to verify this is actually a dictionary or actually responds to the getObjectForKey selector! ***
CFNumberRef idNumber = CFDictionaryGetValue(device, CFSTR("DeviceID"));
if (idNumber) {
uint32_t fetched_id = 0;
CFNumberGetValue(idNumber, 0x3, &fetched_id);
if (fetched_id == device_id) {
result = true;
break;
}
}
}
}
CFRelease(devices);
}
return result;如果这样做正确的话,我有什么建议可以确保我只把设备当作CFDictionary呢?
(我正在处理一些没有详细说明的开源代码,而且它似乎也不是特别可靠。我不确定是数组包含非字典对象的bug,还是包含非字典对象时没有检测到的bug,但在我看来,在这里添加检查不太可能破坏其他代码,然后强迫它只包含其他地方的字典。我不经常使用CoreFoundation,所以我不确定是否使用了合适的术语。)
发布于 2013-12-08 18:04:44
在本例中,由于您正在遍历I/O注册表,所以可以使用CFGetTypeId()
CFTypeRef device = CFArrayGetValueAtIndex(devices, i); // <-- use CFTypeRef
if(CFGetTypeID(device) == CFDictionaryGetTypeID()) { // <-- ensure it's a dictionary
...
}如果您真的需要从C代码向NSObject的接口发送消息,您可以(参见#include <objc/objc.h>和朋友,或者调用.m文件中的C助手函数),但这些策略并不像CFGetTypeID()那样直接,而且更容易出错。
https://stackoverflow.com/questions/20456825
复制相似问题