Sunday, January 16, 2011

How to Check if iOS Supports Class, Method or Keyword

iOS is getting fragmented. More devices to support with major iPhone hardware differences (0-2 cameras, no telephony - 3G - CDMA), screen resolutions (original, double, iPad) and especially more older operating system versions out in the wild.

To reach as many users as possible you have to check whether something exists before you try to use it. Customizing code based on iOS version number is possible, but there are other ways to do it.

Check whether some class is available, might need this with object factory and class specific protocol:

NSString *someClass = @"MyClass";
Class class = NSClassFromString(someClass);
if ([class conformsToProtocol:@protocol(SomeProtocol)])
    id instance = [[class alloc] init];
    [instance someProtocolMethod];
Check whether class supports a method:
if ([item respondsToSelector:@selector(newMethod:)])
   [item newMethod:value];
   [self workAroundFor:item with:value];
Check whether some keyword is available:
if (&UINewKey != nil)
   NSDictionary *dict = [info objectForKey:UINewKey];
   NSDictionary *dict = [self generateDictInfo];
Welcome to the iReal iFragmented iWorld, iOS!


  1. you can also check if an object supports a certain protocol:

    if ([item conformsToProtocol:@protocol(SomeProtocol)])