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

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


当前回答

在Swift的情况下,我们可以实现以下

我们可以创建struct,它允许你创建结构化数据

struct Platform {
    static var isSimulator: Bool {
        #if targetEnvironment(simulator)
            // We're on the simulator
            return true
        #else
            // We're on a device
             return false
        #endif
    }
}

然后,如果我们想检测应用程序是否正在构建的设备或模拟器在Swift然后。

if Platform.isSimulator {
    // Do one thing
} else {
    // Do the other
}

其他回答

在Swift的情况下,我们可以实现以下

我们可以创建struct,它允许你创建结构化数据

struct Platform {
    static var isSimulator: Bool {
        #if targetEnvironment(simulator)
            // We're on the simulator
            return true
        #else
            // We're on a device
             return false
        #endif
    }
}

然后,如果我们想检测应用程序是否正在构建的设备或模拟器在Swift然后。

if Platform.isSimulator {
    // Do one thing
} else {
    // Do the other
}

更新后的代码:

官方声称这是有效的。

#if TARGET_IPHONE_SIMULATOR
NSString *hello = @"Hello, iPhone simulator!";
#elif TARGET_OS_IPHONE
NSString *hello = @"Hello, device!";
#else
NSString *hello = @"Hello, unknown target!";
#endif

原帖(已弃用)

这段代码将告诉您是否在模拟器中运行。

#ifdef __i386__
NSLog(@"Running in the simulator");
#else
NSLog(@"Running on a device");
#endif

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

public static var isSimulator: Bool {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        return true
    #else
        return false
    #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

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

这对我来说很管用:

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