简体   繁体   English

在领域之间切换(iOS / Swift 3)

[英]Switching between realms (iOS / Swift 3)

I was trying to log in or register a user and connect them to an existing realm. 我试图登录或注册用户并将他们连接到现有领域。 Then, depending on the info stored in that realm, I may need them to instead connect to a different realm. 然后,根据存储在该领域中的信息,我可能需要它们代替连接到另一个领域。

Is it not possible to try! 不能尝试! Realm with a different configuration after it is initially configured? 初始配置后,领域是否具有其他配置? Is it discouraged? 灰心吗? Does it need to be done outside of the initial DispatchQueue? 是否需要在初始DispatchQueue之外完成?

Here is the code: 这是代码:

SyncUser.logIn(with: usernameCredentials, server: URL(string: "http://11.22.333.0:9080")!) {
     user, error in
     guard let user = user else {
         fatalError(String(describing: error))
     }

     DispatchQueue.main.async {
         let configuration = Realm.Configuration(
             syncConfiguration: SyncConfiguration(user: user, realmURL: URL(string: "realm://11.22.333.0:9080/ab56realmURL/NameOfRealm1")!)
         )
         self.realm = try! Realm(configuration: configuration)

         if (someCheckOfData in realm) {
              let configuration2 = Realm.Configuration(
                  syncConfiguration: SyncConfiguration(user: user, realmURL: URL(string: "realm://11.22.333.0:9080/ab56realmURL/NameOfRealm2")!)
              )
              self.realm = try! Realm(configuration: configuration2)
         }
      }
}

Thanks so much for any help! 非常感谢您的帮助!

No, it's not discouraged. 不,不气disc。 All you're doing here is creating 2 discrete copies of Configuration , which will then subsequently be creating 2 separate Realm instances on your server. 您在这里要做的只是创建2个离散的Configuration副本,然后将在服务器上创建2个独立的Realm实例。

The two will be completely separate, so there's no chance of causing an exception by incorrectly changing the configuration after it was used to create an initial Realm instance. 两者将是完全分开的,因此在用于创建初始Realm实例之后,通过错误地更改配置是不可能引起异常的。

One thing we do recommend though is not holding onto specific Realm references like that though. 不过,我们建议您做的一件事就是不要坚持使用特定的Realm引用。 They are not thread safe, and GCD isn't guaranteed to execute the same queues on the same threads, so you may be setting yourself up for a future exception. 它们不是线程安全的,并且不能保证GCD在相同的线程上执行相同的队列,因此您可能会为将来的异常做好准备。

If this is going to be your primary Realm, it's usually recommended to set that Configuration as the default Realm one. 如果这将是您的主要领域,通常建议将该Configuration为默认领域。 Otherwise, since Configuration is thread-safe (Assuming you don't modify it later), you can hold onto that, and use it to try! Realm(configuruation:) 否则,由于Configuration是线程安全的(假设您以后不修改它),可以坚持使用它,然后try! Realm(configuruation:)使用它try! Realm(configuruation:) try! Realm(configuruation:) whenever you actually need to use Realm. try! Realm(configuruation:)每当您实际需要使用Realm时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM