让我假设您的迁移代码是:
RealmMigration migration = new RealmMigration() {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
if (oldVersion == 0) {
schema.create("Person")
.addField("name", String.class)
.addField("age", int.class);
// forgot: oldVersion++;
}
}
}
您不能使用版本来确定是否应该添加Person
类或升级版本。但是您可以使用您知道Person
的是否存在,您需要升级版本。
RealmMigration migration = new RealmMigration() {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
if (oldVersion == 0) {
if (schema.contains("Person)) {
oldVersion++;
} else {
schema.create("Person")
.addField("name", String.class)
.addField("age", int.class);
oldVersion++;
}
}
}
}