NSClassFromString to Check for Class Availability

I recently received a question about how to check if a class is available – the specific question was in regards to the TWTweetComposeViewController.

There are two common ways to check for a class. First, if a feature is tied to an OS version, you can check what version of the OS is running. For example, the Twitter framework became available with iOS 5, so with any early version, there is no integrated Twitter support.

A second approach is to use the NSClassFromString method:

Class TweetViewController = NSClassFromString(@"TWTweetComposeViewController");
 
if (TweetViewController != nil)
{ 
  ...
}
else
{
  ...
}

This will check if the TWTweetComposeViewController is available by returning either a class object, or nil if the class is not loaded.

  1. There are a couple of important points to remember. First, if you link to 4.2 or later and deploy to 3.1 or later, you can use the new weak linking features to make this check simpler. See https://developer.apple.com/library/ios/releasenotes/General/WhatsNewIniPhoneOS/Articles/iOS4.html#//apple_ref/doc/uid/TP40010313-SW5

    Second, there are classes (like UINib, introduced in iOS4) that were private in previous versions of the OS and should not be used. So a NSClassFromString check would not be enough. See https://developer.apple.com/library/ios/#releasenotes/General/RN-iPhoneSDK-4_0/_index.html#//apple_ref/doc/uid/TP40009763

Comments are closed.