简体   繁体   中英

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?

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. 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.

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.

One thing we do recommend though is not holding onto specific Realm references like that though. 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.

If this is going to be your primary Realm, it's usually recommended to set that Configuration as the default Realm one. 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:) try! Realm(configuruation:) whenever you actually need to use Realm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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