Swift中的InMemory领域线程 [英] InMemory Realm Threading in Swift

查看:54
本文介绍了Swift中的InMemory领域线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在内存领域中使用一些对象.我通常将对象保存在辅助线程中,并询问主线程中的对象.

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

    }
}

我在辅助线程中调用 _inMemoryRealm ,在主线程中调用 _strongInMemoryRealm ,此配置无效.

I call _inMemoryRealm in secondary threads and _strongInMemoryRealm on main thread, this configuration don't work.

推荐答案

对于初学者,我建议绝对检查以确保未释放您的主线程Realm引用.我个人将使用单个对象将主Realm引用存储在主线程上.这就是您的境界保持空白的最简单原因.

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.

此外,当您在后台对Realm进行写操作时,这些更改仅反映在运行循环的下一次迭代的主线程中.如果需要在此之前反映更改,则可以调用realm.refresh()明确请求它提取最新更改.

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.

这篇关于Swift中的InMemory领域线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆