iosswiftrealmmongodb-realm

How to copy objects from the default local realm to a MongoDB synced realm using Swift?


The alternative title is "How to deep copies data from an offline realm to a synced realm using Swift?"

After found out that the only option for How to upgrade a local realm to a synced realm? is to "clone" or copy all data from the local default realm to the synced realm, then the next question is how to perform the data cloning or copying for a local realm with complicated relationships between data objects.

Is there a recommended approach to copy the data from one realm to a synced realm while keeping the relationship between objects?

There was a realm.copyFromRealm method but seems already deprecated.

Update

Found an official guide on "Add Sync to a Local-Only App", https://docs.mongodb.com/realm/sync/local-to-sync/


Solution

  • Update

    Found a potential workaround for this issue in "How can I easily duplicate/copy an existing realm object" using Codable with JSONEncoder and JSONDecoder, https://stackoverflow.com/a/65436546/2226315

    Found another function in GitHub Gist migrates local realm to a synced realm, however, the code seems already outdated.


    Found a GitHub issue raised in 2014 about how to move/copy objects between realms, https://github.com/realm/realm-cocoa/issues/1076. createInRealm:withObject: was suggested in the comment.

    However, after digging into the source code only createInRealm:withValue: is available in Objective-C API, https://github.com/realm/realm-cocoa/blob/84179b4e0b54e11f73723c283c4567c565da62f5/Realm/RLMObject.h#L174

    In the official guide on "Add Sync to a Local-Only App", there is a section about "Copy Existing Data" which outlines the flow to copy data from a local realm to a synced realm.

    enter image description here

    Relevant Info