iPhone simulator - how to detect when app is running on simulator (so can setup test data)?

I obviously do use something like this ...

#import <TargetConditionals.h>

#if TARGET_IPHONE_SIMULATOR

// Simulator specific code

#else // TARGET_IPHONE_SIMULATOR

// Device specific code

#endif // TARGET_IPHONE_SIMULATOR

And to your second question ... Something like this should help you. In your app delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  if ( ! [[NSUserDefaults standardUserDefaults] boolForKey:@"initialized"] ) {
    // Setup stuff
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"initialized"];
  }

  ... your code ...
}

If you'd like to check on runtime (instead compile time with the # compiler macro) use this code:

UIDevice *currentDevice = [UIDevice currentDevice];
if ([currentDevice.model rangeOfString:@"Simulator"].location == NSNotFound) {
    //running on device
} else { 
    // running in Simulator
}

see also this question: How can I programmatically determine if my app is running in the iphone simulator?


Swift 5:

TARGET_OS_SIMULATOR does not work in Swift 5. targetEnvironment(simulator) works, like below:

#if targetEnvironment(simulator)
// code to run if running on simulator
#else
// code to run if not running on simulator
#endif

Reference