Replace Realm file while app is running

Solutions Collect From Internet About “Replace Realm file while app is running”

Much like deleting a Realm file from disk, it’s only safe to replace a Realm file on disk if your application does not currently have the Realm file open.

From Realm’s documentation on Deleting Realm files:

Because Realm avoids copying data into memory except when absolutely required, all objects managed by a Realm contain references to the file on disk, and must be deallocated before the file can be safely deleted. This includes all objects read from (or added to) the Realm, all List, Results, and ThreadSafeReference objects, and the Realm itself.

In practice, this means that deleting a Realm file should be done either on application startup before you have opened the Realm, or after only opening the Realm within an explicit autorelease pool, which ensures that all of the Realm objects will have been deallocated.

The reason for this is that Realm maintains an in-memory cache of open files, so attempting to open a file that’s already open will result in a reference to the already-open file being returned. This open file will continue to refer to the original file on disk, even if it has since been replaced. Ensuring that all references to Realm accessor objects have been cleaned up means that Realm will not have an existing open file to return, and will instead open the file from disk.

In other words, you must make sure you have no references to Realm’s accessor objects (Realm, Results, ThreadSafeReference or Object instances) at the point when you attempt to replace the Realm file. You must also make sure that any references you did have have since been deallocated (i.e., they’re not lingering in a dispatch queue’s default autorelease pool).

An alternative approach that may be easier to manage is to use a different path when you attempt to reopen the restored file. Since you’re accessing a different path on disk you’ll be guaranteed to open the new file. You’ll still need to make sure you have no references to Realm’s accessor objects since otherwise you’ll get a weird mix of old and new data, but it won’t be as critical that you ensure that the accessor objects were deallocated.