在我的代码中,我确保保存了我的领域对象,并且我确认领域数据库有1个计数 但我从xcode构建并重新运行,我的realm数据库刷新,数据库有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
}
答案 0 :(得分:0)
我自己解决了这个问题。 这是默认Realm()发生的问题。 我假设默认Realm重新刷新。
所以我改变了下面的代码。
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()
}