How do you compact a Realm DB on iOS?

前端 未结 3 1551
粉色の甜心
粉色の甜心 2021-02-08 19:46

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

3条回答
  •  你的背包
    2021-02-08 20:12

    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

提交回复
热议问题