Make Better Things



I like to make better things.

Check iOS version and write conditional code

I strongly recommend not to use iOS version numbers to write conditional code. There is usually a more reliable method of checking whether a particular feature available or not. But if you are in a deadly situation and hardly needed the version number then you can get iOS version number by UIDevice class. Here is the real code –


NSString *currSysVer = [[UIDevice currentDevice] systemVersion];

Here is how you can use this to write conditional code –


// A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer
// class is used as fallback when it isn't available.
NSString *reqSysVer = @"3.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
    displayLinkSupported = TRUE;

Above code works great but writing this condition is real pain every time. The solution of this is Macros. We can use Macros in objective c and reduce the line of code in above code.

Here is real code using Macros –

/*
 *  System Versioning Preprocessor Macros
 */ 

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)


And how we can use these Macros to write conditional code –


/*
 *  Usage
 */ 

if (SYSTEM_VERSION_LESS_THAN(@"4.0")) {
    ...
}

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"3.1.1")) {
    ...
}

Hope these Macros will save someone’s time.

Category: iPhone, Objective-C

Tagged: , ,

3 Responses

  1. Simha says:

    Thanks. It helped a lot!

Leave a Reply