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?
TLDR
Current:
if #available(iOS 9, *)if (@available(iOS 11.0, *))if (NSClassFromString(@"UIAlertController"))Legacy:
if objc_getClass("UIAlertController")if (NSClassFromString(@"UIAlertController"))if ([UIAlertController class])Swift 2+
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:
Note: If you instead attempt to use
objc_getClass(), you will get the following error:Previous versions of Swift
Note that
objc_getClass()is more reliable thanNSClassFromString()orobjc_lookUpClass().Objective-C, iOS 4.2+
See code007’s answer for more details.
OS X or previous versions of iOS
Use
NSClassFromString(). If it returnsnil, 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: