【发布时间】:2016-01-27 18:17:16
【问题描述】:
如何保证在访问领域之前完成领域迁移?迁移领域数据库并开始读取/写入领域似乎存在竞争条件。这是我的问题:
目前,当用户启动应用程序时,我正在使用迁移关闭来设置领域配置。使用 RLMRealmConfiguration.setDefaultConfiguration(config) 设置领域配置后,我设置 RootViewController 并开始访问领域数据。
但是,当需要迁移时,有时会在迁移完成之前访问领域 - 导致崩溃(RLMException:对象已被删除或无效)。如果迁移是一个没有回调的异步任务,我们如何保证它在访问领域之前完成?
这是我的领域配置代码:
class func SetRealmConfigurationForUser(userId: String) {
let config = RLMRealmConfiguration.defaultConfiguration()
// migration setup
config.schemaVersion = 10
config.migrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 2 {
migration.enumerateObjects(ContactUser.className()) { oldObject, newObject in
// Change primary key from PhoneNumber to Phone_BaseId_Key
let phone = oldObject?["PhoneNumber"]
let baseId = oldObject?["BaseId"]
newObject?["Phone_BaseId_Key"] = String(phone) + "_" + String(baseId)
}
}
if oldSchemaVersion < 3 {
migration.enumerateObjects(DigitsContact.className()) { oldObject, newObject in
newObject?["ExternalId"] = ""
}
}
if oldSchemaVersion < 9 {
migration.deleteDataForClassName(DigitsContact.className())
migration.deleteDataForClassName(Address.className())
migration.deleteDataForClassName(Email.className())
migration.deleteDataForClassName(PhoneNumber.className())
}
}
// Use default directory, but replace filename with the userId
config.path = (((config.path! as NSString).stringByDeletingLastPathComponent as NSString)
.stringByAppendingPathComponent(userId) as NSString)
.stringByAppendingPathExtension("realm")
RLMRealmConfiguration.setDefaultConfiguration(config)
【问题讨论】:
标签: objective-c swift migration realm race-condition