在我当前的应用中,我有一个HolderObject(扩展了RealmObject),并带有一个长的“ machineId”.在该应用程序的新版本中,此HolderObject将能够以RealmList的形式包含更多计算机.请参阅以下课程:
旧物件:
public class HolderObject extends RealmObject{
private long machineId;
//.. getters and setters
}
新对象:
public class HolderObject extends RealmObject{
private RealmList<RealmLong> machineIds;
//.. getters and setters
}
其中RealmLong如下:
public class RealmLong extends RealmObject {
private long val;
//.. getters and setters
}
要将所有旧的HolderObject迁移到新对象,请使用我的自定义RealmMigration.如下所示:
public class CustomRealmMigration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
schema.get("HolderObject")
.addRealmListField("machineIds", schema.get("RealmLong"))
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmLong realmLong = realm.createObject(RealmLong.class);
realmLong.setVal(obj.getLong("machineId"));
obj.getList("machineIds").add(realmLong);
realm.commitTransaction();
realm.close();
}
});
}
}
题:
>在obj.getList(“ machineIds”).add(realmLong);行中,出现以下错误:该函数需要DynamicRealmObject,而不是RealmLong.如何将RealmLong添加到此列表?
>(奖金问题)这是解决此迁移问题的正确和最佳方法吗?
解决方法:
像这样做:
schema.get("HolderObject")
.addRealmListField("machineIds", schema.get("RealmLong"))
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
DynamicRealmObject realmLong = realm.createObject("RealmLong");
realmLong.setLong("val", obj.getLong("machineId"));
obj.getList("machineIds").add(realmLong);
}
})
.removeField("machineId");
您创建的realmLong对象必须是DynamicRealmObject.
同样不要忘记在转换后删除旧字段.
请注意,迁移已经包装在事务中,您无需实例化领域对象并自己执行事务.
(Bonus question) Is this the correct and best approach to this migration problem?
想法是好的,执行不是.往上看.
有关迁移的其他信息,请参见github上的this示例和文档.