Move objects between Realms

Hey!

What would be the best way to move objects between 2 distinct Realm instances ?

I tried to manually fetch all objects from one instance and then add them all in the other instance, but, I end up getting an error saying that the object is already managed by other realm.

Object is already managed by another Realm. Use create instead to copy it into this Realm.

I also tried to only declare the object type only in the instance that I want to move the object into, however, in that scenario, I can’t query the objects from the old realm because the object is not declared in there anymore…

Would appreciate some help!
Thanks in advance :slight_smile:

From my understanding, this is not possible. Personally, I convert them to an internal business-logic model and back to realm DTOs. For an easy way, you could use some de/serializer for this task, but it won’t be very efficient.

Super simple - In a nutshell, instantiate an unmanaged object based on the object and write that to the different realm

Some pseudo code:

class PersonClass: Object {
....

Get the object(s)
let person = realm.objects.... //get the person(s) from realm

Create an unmanaged version
let unmanagedPerson = PersonClass(value: person)

write it out

try! differentRealm.write {
   differentReam.add(unmanagedPerson)
}

The key is than an unmanaged object (one that has NOT been written) has it’s realm property set to nil so you can do whatever you want with it. Once’s it’s written, it’s managed and the realm property will not be nil.