Search code examples
iosrealm

Realm.io. How to refresh replaced realm?


I've just created a dropBox backup/restore in my Realm based iOS app. I'm replacing current defaultRealm with the imported one. If I kill the app and restart it, everything works as expected and I see my new imported data but I can't make it appears without restarting the app (even when I've checked the old realm file has been deleted and recreated).

I've tried to reassign the realm path at RLMRealmConfiguration and update the schema version to perform a migration but nothing changes. Is there any way to force a realm to refresh data?


Solution

  • The only way to reliably switch the Realm file is to make sure your app has no strong references to any RLMRealm on any thread.

    If you can guarantee this, then at this point if you delete the underlying Realm file (including the associated files, such as the lock file) and save the new file to that path, you can then call [RLMRealm defaultRealm] and retrieve the new data.

    Here's some code to delete all the associated Realm files:

    NSString *path = [RLMRealm defaultRealmPath];
    
    NSString *fileName = path.lastPathComponent;
    
    NSString *folderPath = [path stringByDeletingLastPathComponent];
    
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:folderPath];
    
    // Enumerate all the files in the folder containing the Realm file    
    for (NSString *filePath in enumerator) {
        // Check to find all the associated Realm files
        if ([filePath containsString:fileName]) {
            NSString *fullPath = [folderPath stringByAppendingPathComponent:filePath];
    
            [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
        }
    }
    

    This issue tracks adding a safe way to delete a Realm file into the API: Issue #2422