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

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


当前回答

在我看来,答案(如上所述,下文重复):

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

是最好的答案,因为它显然是在RUNTIME执行,而不是作为一个COMPILE指令。

其他回答

在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"]) {

}

Swift 4.2 / Xcode 10

我在UIDevice上创建了一个扩展,所以我可以很容易地询问模拟器是否正在运行。

// UIDevice+CheckSimulator.swift

import UIKit

extension UIDevice {
    
    /// Checks if the current device that runs the app is xCode's simulator
    static func isSimulator() -> Bool {        
        #if targetEnvironment(simulator)
            return true
        #else
            return false
        #endif
    }
}

以我的AppDelegate为例,我使用这个方法来决定是否需要注册远程通知,这对于模拟器来说是不可能的。

// CHECK FOR REAL DEVICE / OR SIMULATOR
if UIDevice.isSimulator() == false {
        
    // REGISTER FOR SILENT REMOTE NOTIFICATION
    application.registerForRemoteNotifications()
}

我已经问过了,但题目完全不同。

Xcode在为iPhone编译时设置了什么#定义

我将重复我的回答:

在SDK文档中的“有条件地编译源代码”

相关的定义是TARGET_OS_SIMULATOR,它在iOS框架中的/usr/include/ targetconditions .h中定义。在工具链的早期版本中,你必须这样写:

#include "TargetConditionals.h"

但在当前(Xcode 6/iOS8)的工具链中,这不再是必要的。

例如,如果你想检查你是否在设备上运行,你应该这样做

#if TARGET_OS_SIMULATOR
    // Simulator-specific code
#else
    // Device-specific code
#endif

这取决于哪个适合您的用例。

最好的方法是:

#if TARGET_IPHONE_SIMULATOR

而不是

#ifdef TARGET_IPHONE_SIMULATOR

因为它总是定义为0或1