我有成千上万个字符串,并且根据内容,我想将它们添加到不同的RealmObjects
模型中,并且我有大约10个领域模型,
现在我正在做这样的事情:
if (string.contains("abc")) {
mRealm.beginTransaction();
mRealm.copyToRealmOrUpdate(new ABCModel(string));
mRealm.commitTransaction();
}
if (string.contains("xyz")) {
mRealm.beginTransaction();
mRealm.copyToRealmOrUpdate(new XYZModel(string));
mRealm.commitTransaction();
}
// and so on
我想知道如何将其传递给单个方法来执行事务,而我只需传递字符串和模型类名称,
我如何实现这样的目标:
private void copyToRealm(RealmModel model, String string){
mRealm.beginTransaction();
mRealm.copyToRealmOrUpdate(new model(string));
mRealm.commitTransaction();
}
并称它为
copyToRealm(ABCModel, string);
我想在查询时做同样的事情
public RealmResults<?> queryChemistry(RealmModel model, String year) {
return realm.where(model.class)
.contains("Title", "string")
.findAll();
}
通过模型,我的意思是扩展了类的类RealmObject
。
如果您需要更多信息,请知道我将更新问题,谢谢
老实说,这并不是严格的Realm问题,我个人只是创建一个枚举,该枚举知道如何创建其对应的对象以及如何评估模型是否属于该对象。
public enum Models {
ABC {
@Override
public boolean evaluateIfModel(String input) {
return input.contains("abc");
}
@Override
public RealmModel createModel(String input) {
return new ABCModel(input);
}
};
public abstract boolean evaluateIfModel(String input);
public abstract RealmModel createModel(String input);
}
for(Models model : Models.values()) {
if(model.evaluateIfModel(input)) {
final _model = model;
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(_model.createModel(input));
}
});
break;
}
}
public <T extends RealmModel> RealmResults<T> queryChemistry(T model, String year) {
return realm.where(model.getClass())
.contains("Title", "string")
.findAll();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句