Specifying Simulator Only Code

There are times when you need to write code that is only applicable when working with the simulator.

As an example, I was recently working with an application that required the user to take a picture with their iPhone. Once the picture was taken the application was to show the image to the user, at which point they would measure the size of an object in the image using various controls (movable lines) and a reference object in the image. Problem is, the simulator does not have much for camera functionality (obviously, there is no lens) so any picture taken shows up as a black image.

To get around this problem, I used the compiler directive below and inside the simulator section I would load an image and use the same throughout the application as if it was created from the camera.

#if TARGET_IPHONE_SIMULATOR
  NSLog(@"Running on Simulator");
#else
  NSLog(@"Running on Device");
#endif

Working with a directive such as this is really handy as you can move between testing with the simulator and a real device without having to change any code.

  1. it does not work fine for me ..

    even if i define the TARGET_IPHONE_SIMULATOR in Makefile

    • You don’t need to define TARGET_IPHONE_SIMULATOR, this is system defined. Do you receive a compile time error?

  2. yes, you are right, system defined it. But should add this:

    #ifdef __APPLE__
    #include “TargetConditionals.h”
    #endif

    • Hey Luke,

      Interesting…my compiles fine without the TargetConditionals.h include. Wonder if it has to do with an include somewhere else along the way that itself includes TargetConditionals.h.

      John

Comments are closed.