I'm trying to create a universal iPhone app, but it uses a class defined only in a newer version of the SDK. The framework exists on older systems, but a class defined in the framework doesn't.
I know I want to use some kind of weak linking, but any documentation I can find talks about runtime checks for function existence - how do I check that a class exists?
Current:
if #available(iOS 9, *)
if (@available(iOS 11.0, *))
if (NSClassFromString(@"UIAlertController"))
Legacy:
if objc_getClass("UIAlertController")
if (NSClassFromString(@"UIAlertController"))
if ([UIAlertController class])
Although historically it's been recommended to check for capabilities (or class existence) rather than specific OS versions, this doesn't work well in Swift 2.0 because of the introduction of availability checking.
Use this way instead:
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(...) }
Note: If you instead attempt to use objc_getClass()
, you will get the following error:
⛔️ 'UIAlertController' is only available on iOS 8.0 or newer.
if objc_getClass("UIAlertController") != nil { let alert = UIAlertController(...) } else { let alert = UIAlertView(...) }
Note that objc_getClass()
is more reliable than NSClassFromString()
or objc_lookUpClass()
.
if ([SomeClass class]) { // class exists SomeClass *instance = [[SomeClass alloc] init]; } else { // class doesn't exist }
See code007's answer for more details.
Class klass = NSClassFromString(@"SomeClass"); if (klass) { // class exists id instance = [[klass alloc] init]; } else { // class doesn't exist }
Use NSClassFromString()
. If it returns nil
, the class doesn't exist, otherwise it will return the class object which can be used.
This is the recommended way according to Apple in 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 [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With