检查C风格函数是否存在’MyMethodName()’类型?
此问题适用于iOS版本兼容性。
我知道如果函数存在,如果它是使用respondsToSelector的典型Objective-C样式方法,则该函数是否存在。 即对于如下方法:
- (void) someMethod:(NSInteger)someParameter;
您可以使用:
if ([self respondsToSelector:@selector(someMethod:someParameter)]) { //do something }
但是C风格的function呢? 如何检查是否存在如下函数:
void CStyleFunctionName(FoundationTypeRef parameter);
谢谢!
Xcode(至少从4.3开始)支持弱链接,你可以执行以下操作来查看是否可以调用C函数:
// UIGraphicsBeginImageContextWithOptions() was introduced in iOS 4 in order to support the Retina displays. if (UIGraphicsBeginImageContextWithOptions != NULL) { UIGraphicsBeginImageContextWithOptions(...); } else { UIGraphicsBeginImageContext(); }
动态加载:
#include void *fptr = dlsym(NULL, "CStyleFunctionName"); if (fptr != NULL) { // existent } else { // nonexistent }
另请注意,在C中,没有方法,只有函数。