3
votes

I want to restore the realm swift database the setting section inside my App. I'm able to use FileManager to create and list backups for .realm files. However, when I delete the current realm file, and then copy another realm file to the original realm file location, my App doesn't know recognize that the file content has changed.

In fact, even when I removed the original realm file, and WITHOUT replacing it with anything, my App still functions correctly.

I debugged into the source and I think the issue is that Realm always return the cached version based on the URL. Even if the Url is no longer valid, it still returns the cached realm.

If there any way to force reset the cache so that I can replace the realm file? Seems like Objc allows it, but not in Swift?

Or is there some kind of strong reference that I've missed?

Here's a snippet of the code of deleting the realm file and still being able to access it:


    try! Realm().write {
        // A bunch of adds
    }
    let curURL = Realm.Configuration.defaultConfiguration.fileURL!
    try! FileManager.default.removeItem(at: curURL)

    // Just sample code to make sure things are all cleaned up
    autoreleasepool {
        let realm = try! Realm(fileURL: curURL) // works
        let results = realm.objects(Email.self) // results are from the realm before I delete the file.
    }

1
It's strongly discouraged to try moving, deleting, or otherwise tampering with a Realm file on disk once it's been opened, but as you've seen below you can try it if and only if you invalidate all references to that Realm. - AustinZ

1 Answers

0
votes

Well I think it's really the autoreleasing issue that I'm seeing. If I wrap my code like the following, then the database will be removed correctly.

So that means I will really have to hunt down all of reference in my App ...

class Email: Object {
    dynamic var subject = ""
    dynamic var id = UUID().uuidString

    override static func primaryKey() -> String? {
        return "id"
    }
}

autoreleasepool {
    print("\(try! Realm().configuration.fileURL!.path)")

    try! Realm().write {
        try! Realm().deleteAll()
    }

    try! Realm().write {
        try! Realm().add(Email(value: ["subject": "Hello"]))
        try! Realm().add(Email(value: ["subject": "World"]))
        try! Realm().add(Email(value: ["subject": "Is"]))
        try! Realm().add(Email(value: ["subject": "Good"]))
    }

    var result = try! Realm().objects(Email.self)
    print("\(result.count)")

    try! FileManager.default.removeItem(at: Realm.Configuration.defaultConfiguration.fileURL!)

    var newResult = try! Realm().objects(Email.self)
    print("\(newResult.count)")

}

var newResult = try! Realm().objects(Email.self)
print("\(newResult.count)")