当我重建 ios 模拟器时,如何防止使用 realm.io 刷新数据库?

How to prevent refresh database with realm.io when I rebuild ios simulator?

在我的代码中,我确实保存了我的领域对象,并且我确认领域数据库有 1 个计数。
但我从 xcode 构建并重新运行,我的领域数据库已刷新并且数据库的计数为 0。 为什么领域数据库被清除?以及如何防止刷新? 我认为这不是代码问题而是设置问题...

此外,“/tmp/hogehogerealm2.realm”文件在我重建时没有变化。

// some service model
func createRealm() {
    let realm = RLMRealm(path:"/tmp/hogehogerealm2.realm")

    let storedCredential = FMUserCredential.allObjects()
    if (storedCredential != nil && storedCredential.count >= 1) {
        realm.beginWriteTransaction()
        realm.deleteObjects(storedCredential)
        realm.commitWriteTransaction()
    }

    var credential = FMUserCredential()
    if let atoken = userCredential.token {
        credential.accessToken = atoken
    }
    if let rtoken = userCredential.refreshToken {
        credential.refreshToken = rtoken
    }

    realm.beginWriteTransaction()
    realm.addObject(credential)
    realm.commitWriteTransaction()

    FMUserCredential.allObjects().count // 1
}
-----------------------------
// model of FMUserCredential

import Foundation

class FMUserCredential: RLMObject {
    dynamic var accessToken = ""
    dynamic var refreshToken = ""
    class func find() -> FMUserCredential? {
        println("FMUserCredential.allObjects().count")
        println(FMUserCredential.allObjects().count)
        if (FMUserCredential.allObjects().count >= 1) {
            return FMUserCredential.allObjects().firstObject() as FMUserCredential?
        }
        return nil
    }
}
----------------------------- 
func isUserLoggedIn() -> Bool {
    if (FMUserCredential.find() == nil) {
        return false
    }
    return true
}

我自己解决了这个问题。 这是 defaultRealm() 发生的问题。 我假设 defaultRealm 已刷新重新运行。

所以我更改了如下代码。

import Foundation

class FMUserCredential: RLMObject {
    dynamic var accessToken = ""
    dynamic var refreshToken = ""

    class func realm() -> RLMRealm {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let realmPath = documentsPath.stringByAppendingPathComponent("db.realm")
        let realm = RLMRealm(path:realmPath, readOnly:false, error:nil)
        return realm
    }

    class func findAll() -> RLMResults {
        return FMUserCredential.allObjectsInRealm(realm())
    }
    class func find() -> FMUserCredential? {
        if (findAll().count >= 1) {
            return findAll().firstObject() as FMUserCredential?
        }
        return nil
    }

}

////////////////////////////////////

// client code
let storedCredential = FMUserCredential.findAll()
if (storedCredential.count >= 1) {
    realm.beginWriteTransaction()
    realm.deleteObjects(storedCredential)
    realm.commitWriteTransaction()
}