我的#if TARGET_OS_SIMULATOR代码用于Realm路径定义有什么问题?

ale*_*xey 11 realm swift

我有这个代码

 #if TARGET_OS_SIMULATOR
let device = false
let RealmDB = try! Realm(path: "/Users/Admin/Desktop/realm/Realm.realm")
#else
let device = true
let RealmDB = try! Realm()
#endif
Run Code Online (Sandbox Code Playgroud)

设备bool工作正常,但RealmDB仅适用于其他条件.

rus*_*hop 27

从Xcode 9.3+开始,Swift现在支持if #targetEnvironment(simulator)检查你是否正在为Simulator构建.

请停止使用架构作为模拟器的快捷方式.macOS和模拟器都是x86_64,可能不是你想要的.

// ObjC/C:
#if TARGET_OS_SIMULATOR
    // for sim only
#else
    // for device
#endif


// Swift:
#if targetEnvironment(simulator)
    // for sim only
#else
    // for device
#endif
Run Code Online (Sandbox Code Playgroud)


kis*_*umi 12

TARGET_IPHONE_SIMULATOR宏在Swift中不起作用.你想做的就像下面这样,对吧?

#if arch(i386) || arch(x86_64)
let device = false
let RealmDB = try! Realm(path: "/Users/Admin/Desktop/realm/Realm.realm")
#else
let device = true
let RealmDB = try! Realm()
#endif
Run Code Online (Sandbox Code Playgroud)


zon*_*tar 6

请看这篇文章.这是正确的方法,并且很好地解释了

https://samsymons.com/blog/detecting-simulator-builds-in-swift/

基本上定义一个名为你喜欢的变量(可能是'SIMULATOR'),在模拟器中运行时设置.将其设置为目标的构建设置下Active Compilation Conditions- > Debug然后(+)再选择Any iOS Simulator SDK在下拉列表中,然后添加变量.

然后在你的代码中

var isSimulated = false
#if SIMULATOR
  isSimulated = true // or your code
#endif
Run Code Online (Sandbox Code Playgroud)