正如问题所述,我主要想知道我的代码是否在模拟器中运行,但也有兴趣知道正在运行或正在模拟的特定iphone版本。
编辑:我在问题名称中添加了“以编程方式”这个词。我的问题的要点是能够动态包括/排除代码取决于哪个版本/模拟器正在运行,所以我真的在寻找像一个预处理程序指令,可以为我提供这个信息。
正如问题所述,我主要想知道我的代码是否在模拟器中运行,但也有兴趣知道正在运行或正在模拟的特定iphone版本。
编辑:我在问题名称中添加了“以编程方式”这个词。我的问题的要点是能够动态包括/排除代码取决于哪个版本/模拟器正在运行,所以我真的在寻找像一个预处理程序指令,可以为我提供这个信息。
当前回答
我已经问过了,但题目完全不同。
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
包括所有类型的“模拟器”
NSString *model = [[UIDevice currentDevice] model];
if([model rangeOfString:@"Simulator" options:NSCaseInsensitiveSearch].location !=NSNotFound)
{
// we are running in a simulator
}
///如果它的模拟器不是设备,则返回true
public static var isSimulator: Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return true
#else
return false
#endif
}
在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
}
有人考虑过这里提供的答案吗?
我想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);
}
}