【问题标题】:respondsToSelector: equivalent for CoreFoundation?respondsToSelector:相当于CoreFoundation?
【发布时间】:2013-12-25 17:56:55
【问题描述】:

我有一个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,所以我不确定我是否使用了正确的术语。)

【问题讨论】:

    标签: objective-c c introspection core-foundation respondstoselector


    【解决方案1】:

    在这种情况下,由于看起来您正在遍历 I/O Registry,您可以使用CFGetTypeId()

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

    如果你真的需要从你的 C 代码向NSObject 的接口发送消息,你可以(参见#include &lt;objc/objc.h&gt; 和朋友,或者在 .m 文件中调用 C 辅助函数),但是这些策略是不像CFGetTypeID() 那样直截了当,而且更容易出错。

    【讨论】:

    • 是的。在 CF 世界中,这是正确的解决方案。 (请注意,如果您需要向非 CF Objective-C 对象发送消息,CFGetTypeID 不会帮助您,因为大多数 Objective-C 类没有对应的 CFTypeIDs。您需要投射/桥接至id,然后执行respondsToSelector:。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多