如何解决在领域迁移期间删除List <T>中的类
例如。我有旧型号,像这样:
class Foo:Object {
@objc dynamic var id = ObjectId.generate()
let bars = List<Bar>()
override class func primaryKey() -> String? {
return "id"
}
}
class Bar:Object {
@objc dynamic var id = ObjectId.generate()
override class func primaryKey() -> String? {
return "id"
}
}
和新型号:
class Foo:Object {
@objc dynamic var id = ObjectId.generate()
override class func primaryKey() -> String? {
return "id"
}
}
迁移代码:
let config = Realm.Configuration(
schemaVersion: 1,migrationBlock: {migration,oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.deleteData(forType: "Bar")
}
})
let realm = try! Realm(configuration: config)
如果我先跑
let config = Realm.Configuration(
schemaVersion: 1,oldSchemaVersion in
if oldSchemaVersion < 1 {
}
})
然后运行
let config = Realm.Configuration(
schemaVersion: 2,oldSchemaVersion in
if oldSchemaVersion < 1 {
}
if oldSchemaVersion < 2 {
migration.deleteData(forType: "Bar")
}
})
结果奏效。
这里是问题,这是将两次迁移合并为一次迁移的一种方法吗?
解决方法
我找到了解决方案。只需将两个迁移一起应用。
let url = Realm.Configuration().fileURL!
let schemaVersion = try! schemaVersionAtURL(url)
if schemaVersion == 0 {
autoreleasepool {
let configuration = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before,the version is 0).
schemaVersion: 1,migrationBlock: { migration,oldSchemaVersion in
// We haven’t migrated anything yet,so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {
}
})
_ = try! Realm(configuration: configuration)
}
autoreleasepool {
let configuration = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before,the version is 0).
schemaVersion: 2,so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {
}
if (oldSchemaVersion < 2) {
migration.deleteData(forType: "Bar")
}
})
_ = try! Realm(configuration: configuration)
}
} else {
let configuration = Realm.Configuration(schemaVersion: schemaVersion)
_ = try! Realm(configuration: configuration)
}
autoreleasepool
部分是必需的。否则,不会应用schemaVersion 2。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。