'Close' a Realm to allow file delete


delete the realm files off disk after app start


Realm has a function that allows the developer to delete the local Realm files off disk

let config = Realm.Configuration()
let x = try? Realm.deleteFiles(for: config)

However if realm has been opened or touched in any way e.g. let realm = try! Realm() , realm (in code) is ‘attached’ to those realm files and the function will not allow the files to be deleted.

There’s probably an obvious answer but how does one ‘close’ or ‘deinit’ or even ‘nil’ a Realm after it was touched in code so the realm files can be deleted with that function while the application is running.

I can manually write other code to delete files but even with that, the Realm is re-created because the Realm (in code) is still alive - it seems that function should be able to handle it.

Use Case

Here’s an example;

Suppose we have a ToDo application where the user can create a ToDo list and give it a name. For this case the Realm file is named with that name. (note there are obviously other solutions for naming)

Then the user decides they don’t want that ToDo list at all and wishes to totally delete it

@Jay You guessed it - in Swift, you just set the realm reference to nil - as in

realm = nil

This is a best practice for RealmSwift, especially when dispatching to background threads - once you complete your work on the background, set the reference to nil

Thanks @Ian_Ward

I was a bit unclear. Is this the same behavior for a sync’d realm? The local realm files are stored differently for a sync’d realm than an local only which lead to my (unclear) question.