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_IPHONEandTARGET_IPHONE_SIMULATORto conditionally compile code.Listing 2-1 shows how to use the
TARGET_IPHONE_SIMULATORmacro to determine whether code meant for iOS is being compiled for the simulator or devices.Listing 2-1 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_IPHONEmacro in a source file to be shared between Mac OS X and iOS.Listing 2-2 Determining whether you’re compiling for iOS
#if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #else #import <Cocoa/Cocoa.h> #endifThe
TARGET_OS_IPHONEandTARGET_IPHONE_SIMULATORmacros are defined in theTargetConditionals.hheader 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
本文介绍了如何在iOS应用开发中使用预处理器宏来决定代码是在模拟器还是设备上编译,通过`TARGET_IPHONE_SIMULATOR`和`TARGET_OS_IPHONE`宏实现代码的条件编译。
7887

被折叠的 条评论
为什么被折叠?



