ios - 弱链接 - 检查一个类是否存在并使用该类

标签 ios backwards-compatibility weak-linking

我正在尝试创建一个通用的 iPhone 应用程序,但它使用了一个仅在较新版本的 SDK 中定义的类。该框架存在于旧系统上,但框架中定义的类不存在。

我知道我想使用某种弱链接,但我能找到的任何文档都在谈论运行时检查函数是否存在——如何检查类是否存在?

最佳答案

长见识

电流:

  • Swift:if#available(iOS 9, *)
  • Obj-C,iOS:if (@available(iOS 11.0, *))
  • Obj-C,OS X:if (NSClassFromString(@"UIAlertController"))

旧版:

  • Swift(2.0 之前的版本):if objc_getClass("UIAlertController")
  • Obj-C,iOS(4.2 之前的版本):if (NSClassFromString(@"UIAlertController"))
  • Obj-C、iOS(11.0 之前的版本):if ([UIAlertController class])

swift 2+

虽然历史上建议检查功能(或类是否存在)而不是特定的操作系统版本,但由于引入了 availability checking,这在 Swift 2.0 中效果不佳。 .

改用这种方式:

if #available(iOS 9, *) {
    // You can use UIStackView here with no errors
    let stackView = UIStackView(...)
} else {
    // Attempting to use UIStackView here will cause a compiler error
    let tableView = UITableView(...)
}

注意:如果您改为尝试使用 objc_getClass(),您将收到以下错误:

⛔️ 'UIAlertController' is only available on iOS 8.0 or newer.


Swift 以前的版本

if objc_getClass("UIAlertController") != nil {
    let alert = UIAlertController(...)
} else {
    let alert = UIAlertView(...)
}

注意 objc_getClass() is more reliable than NSClassFromString() or objc_lookUpClass() .


objective-C ,iOS 4.2+

if ([SomeClass class]) {
    // class exists
    SomeClass *instance = [[SomeClass alloc] init];
} else {
    // class doesn't exist
}

参见 code007's answer for more details .


OS X 或以前版本的 iOS

Class klass = NSClassFromString(@"SomeClass");
if (klass) {
    // class exists
    id instance = [[klass alloc] init];
} else {
    // class doesn't exist
}

使用NSClassFromString() .如果返回nil,则该类不存在,否则返回可以使用的类对象。

这是 Apple 在 this document 中推荐的方式:

[...] Your code would test for the existence of [a] class using NSClassFromString() which will return a valid class object if [the] class exists or nil if it doesnʼt. If the class does exist, your code can use it [...]

关于ios - 弱链接 - 检查一个类是否存在并使用该类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3057325/

相关文章:

ios - 使用来自 clang 的 @import?

sdk - 为 Symbian s60 第 3 版开发的应用程序可以在 s60 第 5 版手机上运行吗?

linux - 动态加载和弱符号解析

ios - 用于打印的弱链接框架

ios - 在后端服务中检索 facebook 数据

ios - 在 Swift 中交换数组值

ios - 使用 UITableView 创建照片提要

delphi - Delphi 4 Pro可以在Windows XP(或更高版本)上可靠地安装和使用吗?

java - 如果生产代码针对的是较旧的 JRE,那么在测试代码中使用新的 JDK API 是否安全?

objective-c - 为什么我们在检查符号是否存在时不能使用否定运算符?