7

这个问题是针对 iOS 版本兼容性的。

我知道如何检查函数是否存在,如果它是使用 respondsToSelector 的典型 Objective-C 风格方法。即对于诸如以下的方法:

- (void) someMethod:(NSInteger)someParameter;

您可以使用:

if ([self respondsToSelector:@selector(someMethod:someParameter)]) {
    //do something
}

但是 C 风格的函数呢?如何检查是否存在如下所示的函数:

void CStyleFunctionName(FoundationTypeRef parameter);

谢谢!

4

2 回答 2

11

Xcode(至少从 4.3 开始)支持弱链接,您可以执行以下操作来查看是否可以调用 C 函数:

// UIGraphicsBeginImageContextWithOptions() was introduced in iOS 4 in order to support the Retina displays.
if (UIGraphicsBeginImageContextWithOptions != NULL) {
    UIGraphicsBeginImageContextWithOptions(...);
}
else {
    UIGraphicsBeginImageContext();
}
于 2012-09-20T18:13:31.560 回答
7

动态加载:

#include <dlfcn.h>

void *fptr = dlsym(NULL, "CStyleFunctionName");
if (fptr != NULL) {
    // existent
} else {
    // nonexistent
}

另请注意,在 C 中,没有方法,只有函数。

于 2012-09-20T17:33:01.377 回答