我正在尝试创建一个通用的 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/