0
我想在Realm中保留User
的对象,并且我想只保留单个对象并像单身人士UserProfile.getInstance()
一样将它存在。Realm中的单个对象
那么如何实现呢?
我用它肮脏的方法(如我介意)
public static User getInstance() {
Realm realm = Realm.getDefaultInstance();
User user = realm.where(User.class).findFirst();
if (user != null) {
// If object exists in db
return user;
}
// If object does not exist, we should to create it
realm.executeTransaction(realm -> {
realm.insertOrUpdate(new User());
});
// After create we should to return already 'managed' object.
return realm.where(User.class).findFirst();
}
此代码味道不好,但我没有发现任何更好的解决方案做。另外我在官方文档中找不到任何有用的信息。
如何在Realm中实现singleton
对象?
你使用这种方法吗? – comm1x
@ comm1x你能澄清你的观点吗? –