我想知道如何创建先前从商店检索的领域对象的副本。之后我会用增加的id存储新对象。问题是提到的RealmObject是在领域的早期创建的,因此不存在PrimaryKey等。
感谢您的建议。 丹尼尔
答案 0 :(得分:3)
试试这个:
Product productCopy = realm.copyFromRealm(product);
productCopy.setId(product.getId() + 1);
realm.beginTransaction();
productCopy = realm.copyToRealm(productCopy);
realm.commitTransaction();
productCopy - 是一个新对象,附加到领域,ID增加,字段中的值相同。
答案 1 :(得分:1)
你必须创建另一个对象并将新对象添加到领域事务中的领域
OriginalRealmObject *originalActivity = [OriginalRealmObject objectForPrimaryKey:@"primary key"];
OriginalRealmObject* clonedObject = [[OriginalRealmObject alloc] initWithValue:originalActivity];
[realm beginWriteTransaction];
clonedObject.id = originalActivity.id+1; //make sure is an int property
[OriginalRealmObject createOrUpdateInRealm:realm withValue:clonedObject];
[realm commitWriteTransaction];
答案 2 :(得分:1)
我不确定我是否理解你的问题,如果你想要的是复制一个RealmObject并分配一个不同的主键并存储它,你可以试试这个:
// Get your original RealmObject
YourModel obj1 = realm.where(YourModel.class).findFirst()
// Create a RealmObject instance without proxy, setters won't write to db
YourModel obj2 = new YourModel();
obj2.setField1(obj1.getField1());
obj2.setField2(obj1.getField2());
obj2.setPrimaryKey(obj1.getPrimaryKey()+1);
realm.beginTransaction();
// This will write obj2 to Realm. And the returned YourModel instance
// will be RealmObject with proxy. Setters will write to Realm automatically.
obj2 = realm.copyToRealmOrUpdate(obj2);
realm.commitTransaction();
文档here可能会有所帮助。
答案 3 :(得分:0)
克隆是处理在其他线程中显示realmObjects时的解决方案,例如Widgets的情况。我一直看到异常从其他线程尝试Realm。我使用了一个RealmList列表,并克隆了它的对象。好的..我稍后会说明我的意思..