正如问题所述,我主要想知道我的代码是否在模拟器中运行,但也有兴趣知道正在运行或正在模拟的特定iphone版本。

编辑:我在问题名称中添加了“以编程方式”这个词。我的问题的要点是能够动态包括/排除代码取决于哪个版本/模拟器正在运行,所以我真的在寻找像一个预处理程序指令,可以为我提供这个信息。


当前回答

我的回答是基于@Daniel Magnusson的回答和@Nuthatch和@n.Drake的评论。我写它是为了为在iOS9及以后的系统上快速工作的用户节省一些时间。

这对我来说很管用:

if UIDevice.currentDevice().name.hasSuffix("Simulator"){
    //Code executing on Simulator
} else{
    //Code executing on Device
}

其他回答

Swift现在有了更好的方式。

从Xcode 9.3及更新版本开始,你可以使用#if targetEnvironment(模拟器)来检查。

#if targetEnvironment(simulator)
//Your simulator code
#endif

所有这些答案都很好,但它在某种程度上让像我这样的新手感到困惑,因为它没有阐明编译检查和运行时检查。预处理器在编译之前,但我们应该更清楚

这篇博客文章展示了如何检测iPhone模拟器?很明显

运行时

首先,让我们简单讨论一下。UIDevice已经为您提供了有关设备的信息

[[UIDevice currentDevice] model]

将根据应用程序运行的位置返回“iPhone模拟器”或“iPhone”。

编译时

但是,您需要的是使用编译时定义。为什么?因为你严格编译你的应用程序,要么在模拟器中运行,要么在设备上运行。苹果做了一个叫做TARGET_IPHONE_SIMULATOR的定义。让我们看一下代码:

#if TARGET_IPHONE_SIMULATOR

NSLog(@"Running in Simulator - no app store or giro");

#endif

在Swift 4.2 (Xcode 10)中,我们可以做到这一点

#if targetEnvironment(simulator)
  //simulator code
#else 
  #warning("Not compiling for simulator")
#endif

我的回答是基于@Daniel Magnusson的回答和@Nuthatch和@n.Drake的评论。我写它是为了为在iOS9及以后的系统上快速工作的用户节省一些时间。

这对我来说很管用:

if UIDevice.currentDevice().name.hasSuffix("Simulator"){
    //Code executing on Simulator
} else{
    //Code executing on Device
}

包括所有类型的“模拟器”

NSString *model = [[UIDevice currentDevice] model];
if([model rangeOfString:@"Simulator" options:NSCaseInsensitiveSearch].location !=NSNotFound)
{
    // we are running in a simulator
}