title: How to switch database?
body: <p>We have the need to switch between different databases, i.e., realms. There is an active database at a specific folder (e.g., ".../database/some.realm"), and this database may change (e.g., to ".../database/other.realm").</p>
  
  <p>What we are currently doing is this:</p>
  
  <p>(1) for the previous operational database: Commit any open transactions and invalidate.</p>
  
  <pre><code>        if realm.inWriteTransaction {               
              do {                    
                  try realm.commitWrite()
              } catch {
                  ...
              }
          } else {
              ...
          }
          realm.invalidate()
  </code></pre>
  
  <p>(2) move the previous database to a new place.</p>
  
  <p>(3) move the new database to the operational place.</p>
  
  <p>(4) for the new database: create a new configuration and create a new realm.</p>
  
  <pre><code>public func openDatabaseAtURL(url: NSURL) {
      let config = Realm.Configuration(
          fileURL: url,
          inMemoryIdentifier: nil,
          encryptionKey: nil,
          readOnly: false,
          schemaVersion: self.currentSchemaVersion,
          migrationBlock: nil,
          deleteRealmIfMigrationNeeded: false,
          objectTypes: nil)
      do {
          let realm = try Realm(configuration: config)
          self.realm = realm
      } catch let error as NSError {
          ...
      } catch {
          ...
      }
  }
  </code></pre>
  
  <p>Although there are no errors, and the new database is used properly when the app is started the next time, we want to have the database switch operational immediately. However, realm seems not to notice that there was something happening, as in the folder none of the realm's additional files (.lock etc) are created, and the app still shows old data after refreshing.</p>
  
  <p>What are we doing wrong, and what should we do instead? (In other words: how do we properly "close" the old database and "open" the new one?)</p>
  
  <p>Thanks a lot for your help!</p>
  
  <ul>
  <li>Hardy</li>
  </ul>