这是我解决它的方式 -
override fun migrate(realm: DynamicRealm, oldVersion1: Long, newVersion: Long) {
if (oldVersion == 2L) {
val routeSchema = schema.get("Route")
val directionSchema = schema.get("Direction")
/*
Creating a new temp field called isLinked which is set to true for those which are
references by Route objects. Rest of them are set to false. Then removing all
those which are false and hence duplicate and unnecessary. Then removing the temp field
isLinked
*/
directionSchema!!
.addField("isLinked", Boolean::class.java)
.transform { obj ->
//Setting to false for all by default
obj.set("isLinked", false)
}
routeSchema!!.transform { obj ->
obj.getList("directionList").forEach {
//Setting to true for those which are referenced
it.set("isLinked", true)
}
}
//Removing all those which are set as false
realm.where("Direction")
.equalTo("isLinked", false)
.findAll()?.deleteAllFromRealm()
directionSchema.removeField("isLinked")
//Rest of the migration
}
}
我发现了更多的东西。根据这个关于 Realm 的内容非常丰富的演讲 - https://academy.realm.io/posts/jp-simard-realm-core-database-engine/(跳到 28:45),有办法删除所有那些未引用的节点来自 B 树。但是,我找不到这样做的方法。Realm.compactRealm()
似乎是一种方法,但没有奏效。