Reputation: 91
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. }
Upvotes: 3
Views: 1604
Reputation: 91
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)")
Upvotes: 0