InMemory Realm Threading in Swift

邮差的信 提交于 2019-12-12 19:22:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41002022/inmemory-realm-threading-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!