ios - 检查 Swift 中是否存在全局函数

标签 ios swift introspection

是否可以检测是否定义了某些全局函数(不是类方法)(在 iOS 中)?类似于类中的 respondsToSelector...

最佳答案

Swift 目前不支持查找全局函数。

对于 C 函数(Apple 框架中的大多数全局函数都是 C 函数)至少有两种方法:

  • 使用弱链接符号
  • 动态链接器 API:dlopen

两者都动态检查(在运行时)是否可以找到符号。

这是一个检查 UIGraphicsBeginImageContextWithOptions(在 iOS 4 中引入)是否可用的示例:

void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) __attribute__((weak));

static inline BOOL hasUIGraphicsBeginImageContextWithOptions() {
    return UIGraphicsBeginImageContextWithOptions != NULL;
}

这是相同的检查,使用 dlsym:

#import <dlfcn.h>

static inline BOOL hasUIGraphicsBeginImageContextWithOptions() {
    return dlsym(RTLD_SELF, "UIGraphicsBeginImageContextWithOptions") != NULL;
}

使用 dlsym 的优点是您不需要声明,而且它很容易移植到 Swift 中。

关于ios - 检查 Swift 中是否存在全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38353450/

相关文章:

ios - ‘SEL' 类型的集合元素不是 Objective-C 对象

iphone - 如何从我的应用程序中的存折访问通行证?

swift - 将委托(delegate)从 NSWindowController 子类传递到我的 ViewController 时出现问题

python - Python 中 dir() 和 __dict__ 的最大区别是什么

python - 如何从 Python 类中查找属性名称

ios - Xamarin + Monotouch:无法自动运行程序集“.../obj/iPhone/Release/mtouch-cache/Build/Touch.exe”(MT3001)

ios - 在 iOS 中解析 JSON 并将结果存储到 Array

ios - 调度定时器源中的数据争用

ios - 如何在同一函数中为 2 个 Alamofire 请求只有 1 个完成处理程序

c++ - 为什么在 Qt 源代码文件末尾包含 ".moc"文件很重要?