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



我有这个代码

 #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

设备bool运行良好,但RealmDB仅适用于else条件。

从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

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

请看这篇文章。这是正确的方法,对此有很好的解释

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

基本上定义一个您喜欢命名的变量(可能是"SIMULATOR"),以便在模拟器运行期间进行设置。在Target的Build Settings中设置,在Active Compilation Conditions->Debug下,然后在(+)下,在下拉列表中选择Any iOS Simulator SDK,然后添加变量。

然后在你的代码

var isSimulated = false
#if SIMULATOR
  isSimulated = true // or your code
#endif

关于这个问题的更多解释在这里。我正在使用这种方法:

struct Platform {
        static let isSimulator: Bool = {
            var isSim = false
            #if arch(i386) || arch(x86_64)
                isSim = true
            #endif
            return isSim
        }()
    }
    // Elsewhere...
    if Platform.isSimulator {
        // Do one thing
    }
    else {
        // Do the other
    }

或者创建一个实用程序类:

class SimulatorUtility
{
    class var isRunningSimulator: Bool
    {
        get
        {
             return TARGET_OS_SIMULATOR != 0// for Xcode 7
        }
    }
}

最新更新