全局领域对象:单例还是每次都获取? [英] Global Realm Object: Singleton or Fetch It Every Time?

查看:55
本文介绍了全局领域对象:单例还是每次都获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要对 currentUser 进行全局访问,它是一个 User 类的实例,定义如下:

In my app I need to have global access to a currentUser which is an instance of a User class defined like this:

class User: Object{
  @objc dynamic var recordName = UUID().uuidString
  @objc dynamic var name = ""
  @objc dynamic var email = ""
  @objc dynamic var photo: Data? = nil

  override static func primaryKey() -> String? {
    return "recordName"
  }
}

currentUser 是在应用启动时建立的,我在我的应用中几乎到处都经常提到它.

The currentUser is established when the app launches, and I refer to it frequently almost everywhere in my app.

我注意到,我不时收到一个错误,似乎是由于在不同位置引用此 currentUser 引起的:

I've noticed that from time-to-time, I get an error that appears to be caused by referencing this currentUser in different places:

从错误线程访问的领域

我能够在大多数情况下跟踪 Realm 所在的线程,但很难涵盖所有情况.所以这引出了我的问题.

I'm able to keep track of which thread Realm is on most of the time, but it's difficult to cover all cases. So this leads me to my question.

是否有一种安全的方法可以将 currentUser 对象设置为单例对象?或者我应该将他们的 ID 保存到磁盘,然后在每次需要时从 Realm 获取对象(如下所示)?

Is there a safe way to set the currentUser object once as a singleton? Or should I save their ID to disk and then fetch the object from Realm every time I need it (something like below)?

let realm = try! Realm()
if let currentUserId = defaults.string(forKey: "currentUserId"), let user = realm.object(ofType: User.self, forPrimaryKey: currentUserId){
  currentUser = user
}

我在 Xcode 10 上使用 Swift 4.2.谢谢!

I am using Swift 4.2 on Xcode 10. Thanks!

推荐答案

只要你能确保你总是从同一个线程访问你的 currentUser 对象,就可以将它设置为一个全局可访问的对象,并使用自动更新的引用,而不是每次从 Realm 重新获取它.

As long as you can make sure that you always access your currentUser object from the same thread, it's fine to set it up as a globally accessible object once and use that auto-updating reference to it instead of re-fetching it every time from Realm.

您可以通过为 Realm 创建一个专用线程并始终在访问 Realm/currentUser 之前调度到该线程或简单地从系统线程执行此操作来实现这一点,例如 DispatchQueue.main.

You can achieve this by either creating a dedicated thread to Realm and always dispatching to that thread before accessing Realm/currentUser or simply doing it from a system thread, such as DispatchQueue.main.

这篇关于全局领域对象:单例还是每次都获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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