Conditional compile when running in Simulator as opposed to on a device

烈酒焚心 提交于 2019-12-03 04:46:08

问题


Is there a compiler directive I can use to compile a different line of code when targetting the simulator as opposed to my device. Something like:

# IF SIMULATOR
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
# ELSE
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
# END

EDIT

Direct link to docs.


回答1:


#if TARGET_IPHONE_SIMULATOR
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
#else
[self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
#endif



回答2:


Update: (Deprecated/Obsolete) This only worked for a few years, and does not work any more. (10+ years later)

For the record, here's another method which Apple uses in some of their official Sample Code:

#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



回答3:


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 

The target environment platform condition feature was introduced by SE-0190 and is available since Swift 4.1.



来源:https://stackoverflow.com/questions/864920/conditional-compile-when-running-in-simulator-as-opposed-to-on-a-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!