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

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


当前回答

用swift:

#if (arch(i386) || arch(x86_64))
...            
#endif

从检测应用程序是否正在构建的设备或模拟器在Swift

其他回答

///如果它的模拟器不是设备,则返回true

public static var isSimulator: Bool {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        return true
    #else
        return false
    #endif
}

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

我想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.2 (Xcode 10)中,我们可以做到这一点

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

这对我来说是最有效的

NSString *name = [[UIDevice currentDevice] name];


if ([name isEqualToString:@"iPhone Simulator"]) {

}

我有同样的问题,TARGET_IPHONE_SIMULATOR和TARGET_OS_IPHONE总是定义,并设置为1。Pete的解决方案当然有效,但如果你碰巧构建在英特尔以外的东西上(不太可能,但谁知道呢),这里有一些东西是安全的,只要iphone硬件不改变(所以你的代码将永远适用于当前的iphone):

#if defined __arm__ || defined __thumb__
#undef TARGET_IPHONE_SIMULATOR
#define TARGET_OS_IPHONE
#else
#define TARGET_IPHONE_SIMULATOR 1
#undef TARGET_OS_IPHONE
#endif

把它放在方便的地方,然后假装TARGET_*常量是正确定义的。