【发布时间】:2017-07-04 06:04:21
【问题描述】:
您好,我有 Realm 迁移,但遇到错误
下面是我的情况错误场景
第一
我有一个简单的User 模型,schemeVersion 0(默认)
class User: Object {
dynamic var username = ""
dynamic var date = NSDate()
}
在版本 1 中添加 date2
class User: Object {
dynamic var username = ""
dynamic var date = NSDate()
dynamic var date2 = NSDate()
}
并迁移
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if oldSchemaVersion < 1 {
migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
newObject!["date2"] = oldObject!["date"] as! NSDate
})
}
}
在版本 3 中添加 date3 并在版本 4 中将 date3 重命名为 date 4
class User: Object {
dynamic var username = ""
dynamic var date = NSDate()
dynamic var date2 = NSDate()
dynamic var date4 = NSDate()
}
并迁移
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 4,
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if oldSchemaVersion < 1 {
migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
newObject!["date2"] = oldObject!["date"] as! NSDate
})
}
if oldSchemaVersion < 2 {
migration.enumerateObjects(ofType: RealmUser.className(), { (oldObject, newObject) in
newObject!["date3"] = oldObject!["date2"] as! NSDate
})
}
if oldSchemaVersion < 3 {
migration.renameProperty(onType: User.className(), from: "date3", to: "date4")
}
}
当我按顺序迁移 0 -> 1 -> 2 -> 3 -> 4 时工作正常
但是当从 0 版本迁移到 4 版本时会导致 fatal error: 'try!' expression unexpectedly raised an error
"Cannot rename property 'User.date3' because it does not exist."
在这种情况下,我如何将 0 ~ 3 版本迁移到 4 而没有上述不存在的例外?
【问题讨论】:
标签: ios swift migration realm version