I'm trying to use in memory realm to store some objects. I usually save objects in a secondary thread and ask for objects on main thread.
I also need to have a strong reference to the in memory Realm, in order to avoid data loss.
static private var _strongInMemoryRealm: Realm? = {
return VideoObject._inMemoryRealm
}()
static private var _inMemoryRealm: Realm? {
get {
var realm: Realm? = nil
let config = Realm.Configuration(inMemoryIdentifier: "InMemoryRealm")
do {
realm = try Realm(configuration: config)
} catch let error {
debugPrint("Realm could not be opened: ", error)
Crashlytics.sharedInstance().recordError(error)
}
return realm
}
}
I call _inMemoryRealm in secondary threads and _strongInMemoryRealm on main thread, this configuration don't work.
For starters, I'd recommend absolutely checking to make sure your main thread Realm reference isn't being deallocated. I personally would use a singleton object to store the main Realm reference on the main thread. That would be the simplest reason why your Realm is staying empty.
Beyond that, when you do a write to a Realm in the background, those changes are only reflected in the main thread on the next iteration of the run loop. If you need the changes to be reflected before that, you can call
realm.refresh()
to explicitly request it to pull the latest changes.