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

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


当前回答

有人考虑过这里提供的答案吗?

我想objective-c的等价物是

+ (BOOL)isSimulator {
    NSOperatingSystemVersion ios9 = {9, 0, 0};
    NSProcessInfo *processInfo = [NSProcessInfo processInfo];
    if ([processInfo isOperatingSystemAtLeastVersion:ios9]) {
        NSDictionary<NSString *, NSString *> *environment = [processInfo environment];
        NSString *simulator = [environment objectForKey:@"SIMULATOR_DEVICE_NAME"];
        return simulator != nil;
    } else {
        UIDevice *currentDevice = [UIDevice currentDevice];
        return ([currentDevice.model rangeOfString:@"Simulator"].location != NSNotFound);
    }
}

其他回答

适用于Swift 4.1及更新版本和Xcode 9.3及更新版本

使用以下代码:

#if targetEnvironment(simulator)
   // Simulator
#else
   // Device
#endif

不是预处理器指令,但这是我在研究这个问题时所寻找的;

NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
    //device is simulator
}

Swift现在有了更好的方式。

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

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

之前的答案有点过时了。我发现所有你需要做的是查询TARGET_IPHONE_SIMULATOR宏(不需要包括任何其他头文件[假设你是为iOS编码])。

我尝试了TARGET_OS_IPHONE,但它在实际设备和模拟器上运行时返回相同的值(1),这就是为什么我建议使用TARGET_IPHONE_SIMULATOR代替。

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

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