gpt4 book ai didi

objective-c - respondsToSelector:相当于 CoreFoundation?

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:22 24 4
gpt4 key购买 nike

我有一个 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 的任何建议?

(我正在处理一些没有特别详细记录的开源代码,而且它似乎也不是特别可靠。我不确定是否是数组包含非字典对象的错误或者当它包含非字典对象时它没有检测到的错误,但在我看来,在这里添加检查不太可能破坏其他代码然后强制它只包含其他地方的字典。我不经常使用CoreFoundation,所以我不确定我是否使用了正确的术语。)

最佳答案

在这种情况下,由于看起来您正在遍历 I/O 注册表,因此您可以使用 CFGetTypeId() :

CFTypeRef device = CFArrayGetValueAtIndex(devices, i);  // <-- use CFTypeRef
if(CFGetTypeID(device) == CFDictionaryGetTypeID()) { // <-- ensure it's a dictionary
...
}

如果确实需要发消息到NSObject的接口(interface),您可以(参见 #include <objc/objc.h> 和 friend ,或调用 .m 文件中的 C 辅助函数),但这些策略不像 CFGetTypeID() 那样直接。 ,而且更容易出错。

关于objective-c - respondsToSelector:相当于 CoreFoundation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20456825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com