2

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.

Marco
  • 1,057
  • 1
  • 19
  • 36
  • Why doesn't it work exactly? What does it do? – TiM Dec 06 '16 at 19:09
  • I save the objects on a background thread. On the same thread with the same realm **_inMemoryRealm** i can get the objects. Back on the main thread the realm instance **_strongInMemoryRealm** return me an empty array – Marco Dec 06 '16 at 19:31

1 Answers1

2

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.

Community
  • 1
  • 1
TiM
  • 15,812
  • 4
  • 51
  • 79