Compiling Source Code Conditionally for iOS Applications
There may be times when you need to run code on the simulator but not on a device, and the other way around. On those occasions, you can use the preprocessor macros
TARGET_OS_IPHONE
andTARGET_IPHONE_SIMULATOR
to conditionally compile code.Listing 2-1 shows how to use the
TARGET_IPHONE_SIMULATOR
macro to determine whether code meant for iOS is being compiled for the simulator or devices.Determining whether you’re compiling for the simulator
// Set hello to "Hello, <device or simulator>"! #if TARGET_IPHONE_SIMULATOR NSString *hello = @"Hello, iOS Simulator!"; #else NSString *hello = @"Hello, iOS device!"; #endifListing 2-2 shows how to use the
TARGET_OS_IPHONE
macro in a source file to be shared between Mac OS X and iOS.Determining whether you’re compiling for iOS
#if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #else #import <Cocoa/Cocoa.h> #endifThe
TARGET_OS_IPHONE
andTARGET_IPHONE_SIMULATOR
macros are defined in theTargetConditionals.h
header file.
例子:
#ifdef __APPLE__
#include "TargetConditionals.h"
#endif
#if TARGET_IPHONE_SIMULATOR NSString *hello = @”Hello, iPhone simulator!”; #elif TARGET_OS_IPHONE NSString *hello = @”Hello, device!”; #else NSString *hello = @”Hello, unknown target!”; #endif