在Simulator中运行时的条件编译,而不是在设备上运行

Cod*_*eef 31 iphone objective-c compiler-directives ios ios-simulator

有没有一个编译器指令,我可以用它来编译一个不同的代码行来定位模拟器而不是我的设备.就像是:

# IF SIMULATOR
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
# ELSE
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
# END
Run Code Online (Sandbox Code Playgroud)

编辑

直接链接到文档.

Cod*_*eef 55

#if TARGET_IPHONE_SIMULATOR
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
#else
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
#endif
Run Code Online (Sandbox Code Playgroud)


Ell*_*iot 11

为了记录,这是Apple在其官方示例代码中使用的另一种方法:

#if TARGET_CPU_ARM
  // Only executes on an iPhone or iPod touch device
  [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
#else
  // Only executes on the Simulator
  [self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
#endif
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,似乎Apple的示例代码是错误的,如果他们更改了设备(或Mac)的架构,这段代码就会中断. (4认同)

Pau*_*tos 5

For those looking for a modern Swift solution, the (new) platform condition targetEnvironment provides the definitive answer here. For instance:

#if targetEnvironment(simulator)
self.imagePicker.sourceType = .photoLibrary
#else
self.imagePicker.sourceType = .camera
#endif 
Run Code Online (Sandbox Code Playgroud)

目标环境平台状态的功能是由推出SE-0190,并提供自雨燕4.1