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
It can be indeed tricky to completely tear down all retrieved model accessors, but there is unfortunately no other way to close a Realm.
As you wrote "periodically" every app launch might be often enough, depending on your use case.
On the launch of your application, it should be still relatively easy to open Realm in a dedicated autoreleasepool, write a compacted copy to a different path and replace your default.realm file with it.
func compactRealm() {
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
let defaultParentURL = defaultURL.URLByDeletingLastPathComponent!
let compactedURL = defaultParentURL.URLByAppendingPathComponent("default-compact.realm")
autoreleasepool {
let realm = try! Realm()
realm.writeCopyToPath(compactedURL)
}
try! NSFileManager.defaultManager().removeItemAtURL(defaultURL)
try! NSFileManager.defaultManager().moveItemAtURL(compactedURL, toURL: defaultURL)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
compactRealm()
// further setup …
return true
}
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)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
compactRealm()
// further setup …
return true
}