gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:46 28 4
gpt4 key购买 nike

是否可以检测是否定义了某些全局函数(不是类方法)(在 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/

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