Replace Realm file while application is running

To implement the backup / restore function, I delete the existing Realm database file and replace it with a new database file with the same name. However, when the application starts, it does not see the contents of the new database file. If I leave and restart the application, it will see the contents of the new database file. Is there a way for the application to see the new content without having to restart it?

+4
ios swift realm
source share
1 answer

Like deleting a Realm file from disk, it is safe to replace the Realm file on disk if your application does not currently open the Realm file.

From the Realm documentation on Removing Realm Files :

Since Realm avoids copying data to memory, unless absolutely necessary, all objects managed by Realm contain links to a file on disk and must be freed before the file can be safely deleted. This includes all objects read from (or added to) the Kingdom, all List , Results and ThreadSafeReference and Realm objects.

In practice, this means that deleting the Realm file must be done either at application startup before you open Realm, or only after opening Realm in an explicit auto-detection pool, which ensures that all Realm objects are redistributed.

The reason for this is that Realm supports open access cache memory, so an attempt to open a file that has already opened will result in a link to the returned file of an already open file. This open file will continue to reference the original file on disk, even if it has since been replaced. To make sure that all references to Realm access objects have been cleared means that Realm will not have an existing open file to return and will open the file from disk instead.

In other words, you must make sure that you do not have references to Realm access objects ( Realm , Results , ThreadSafeReference or Object ) at the moment you are trying to replace the Realm file. You should also make sure that since then all the links that you had have been freed (i.e., they do not linger in the default startup pool for the send queue).

An alternative approach, which may be easier to manage, is to use a different path when trying to reopen the restored file. Since you are accessing another path on the disk, you are guaranteed to open a new file. You still need to make sure that you do not have references to Realm access objects, because otherwise you will get a strange combination of old and new data, but it will not be so important that you guarantee the release of accessory objects.

+4
source share

All Articles