Xcode、iPhone:如何在编译时检测模拟器目标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3007215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:26:37  来源:igfitidea点击:

Xcode, iPhone: How to detect simulator target at compile time?

iphonexcodeios-simulator

提问by Thomas Tempelmann

I wonder if, when building an iPhone app for the Simulator, there are special DEFINEs added that allow me to conditionally compile for this case?

我想知道在为模拟器构建 iPhone 应用程序时,是否添加了特殊的 DEFINE 允许我有条件地针对这种情况进行编译?

If not, I'll have to add my own targets for this case, but I'd rather have an automatic way of detection.

如果没有,我将不得不为这种情况添加我自己的目标,但我宁愿有一种自动检测方式。

Alternatively, is there a dynamic way to know when my code runs on the Simulator, I mean something that's documented? I've been searching the docs for a while now but had no luck yet.

或者,是否有一种动态方式可以知道我的代码何时在模拟器上运行,我的意思是有记录的内容?我一直在搜索文档一段时间,但还没有运气。

回答by Vladimir

For compile-time check you need TARGET_IPHONE_SIMULATOR defined in TargetConditionals.h

对于编译时检查,您需要在 TargetConditionals.h 中定义 TARGET_IPHONE_SIMULATOR

#if TARGET_IPHONE_SIMULATOR
// Simulator code
#endif

For run-time check you can use for example -modelmethod in UIDevice. For iPhone simulator it returns iPhone Simulatorstring (not sure about iPad simulator though)

对于运行时检查,您可以使用-modelUIDevice 中的示例方法。对于 iPhone 模拟器,它返回iPhone Simulator字符串(虽然不确定 iPad 模拟器)

回答by kaushal

@Update :
In iOS 9.0 SDK, TARGET_IPHONE_SIMULATOR is - DEPRECATED. use TARGET_OS_SIMULATOR instead of TARGET_IPHONE_SIMULATOR

@更新:
在 iOS 9.0 SDK 中,TARGET_IPHONE_SIMULATOR 已弃用。使用 TARGET_OS_SIMULATOR 而不是 TARGET_IPHONE_SIMULATOR

#if TARGET_OS_SIMULATOR
  // Simulator code
#endif

from Swift 4.1:

从 Swift 4.1 开始:

#if targetEnvironment(simulator)
    // code for the simulator here
#else
   // code for real devices here
#endif