Picture of Brian Love wearing black against a dark wall in Portland, OR.

Brian Love

Target Conditionals in Objective-C

When developing an application I want to be able to set a variable based on the target. In other words I want to know if I am running my app on the simulator or on my device. In this example I want to set a URL for testing against a local REST service, versus having the URL for the production REST service. This is pretty simple to do using the Target Conditionals in Objective-C. We can test if we are deploying to the simulator or to an iPhone.

Preprocessor Directives

In Objective-C you can defined preprocessor directives. What are they? Basically, before our code is sent off to the compiler, it is preprocessed to make the human readable code ready for the compiler. During this step, any preprocessor directives are defined. The value that we define for these constant variables are then literally replaced throughout our code. For example, if we define a preprocessor directive such as:

#define MAXNUMBERS64
int numberPool[MAXNUMBERS]

Then, after the precompile phase, our code will look like:

int numberPool[64]

In this example, the value for MAXNUMBERS is stored as 64. This value is literally replaced throughout our code anywhere we use the constant “MAXNUMBERS”.

TargetConditionals.h

In Objective-C we have a header file named TargetConditionals.h that stores a variety of conditionals that we can use to determine which operating system we are targeting our code for. Some of these conditionals include:

Using these, we can tell the preprocessor to include certain sections of code for compiling, or not. We use the #ifdef — #else — #endif preprocessing conditionals. Here is the code that I used to set the URL based on if I am running the code on my simulator or on my physical device:

#if TARGET_IPHONE_SIMULATOR
  NSString *urlString = @"http://local.acuity-apps.com/api/index.cfm/api";
#else
  NSString *urlString = @"http://www.acuity-apps.com/api/index.cfm/api";
#endif

Hope this helps you as you work on developing applications that require you to have code that is specific to your targeted operating system.