I\'d like to compact a Realm instance on iOS periodically to recover space. I think the process is to copy the db to a temporary location, then copy it back and use the new defa
The answer given by @marius has an issue: the open Realm might still reference the deleted file. This means some writes might end up in the old (deleted) file, causing the app to lose data.
The correct implementation of compactRealm method looks like this (swift 3):
func compactRealm() {
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
let defaultParentURL = defaultURL.deletingLastPathComponent()
let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
autoreleasepool {
let realm = try! Realm()
try! realm.writeCopy(toFile: compactedURL)
}
try! FileManager.default.removeItem(at: defaultURL)
try! FileManager.default.moveItem(at: compactedURL, to: defaultURL)
}
This issue has been driving me crazy until I found an answer here