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

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


当前回答

Swift现在有了更好的方式。

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

#if targetEnvironment(simulator)
//Your simulator code
#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

如果没有效果,试试这个

public struct Platform {

    public static var isSimulator: Bool {
        return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer
    }

}

更新后的代码:

官方声称这是有效的。

#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

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

这对我来说很管用:

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