Realm Swift iOS - safely deleting and re-keying an encrypted Realm
<p>Does Realm Swift have some way to safely delete and create a new encrypted Realm file with a new key (but the same file name)?</p>

<p>My use case: when a user logs out of my app, I delete the encrypted .realm file, since the encryption key will also be deleted: </p>

<pre><code>static func deleteRealm() {
  let configuration = Realm.Configuration()    
  let path = NSURL.fileURLWithPath(configuration.path!)     
                  .URLByDeletingLastPathComponent?
                  .URLByAppendingPathComponent("encrypted.realm")
                  .path!
  if NSFileManager.defaultManager().fileExistsAtPath(path) {
      // Delete realm
      try! NSFileManager.defaultManager().removeItemAtPath(path)
    }
  }
}
</code></pre>

<p>(Unfortunately, calling <code>realm.deleteAll()</code> will not suffice, since there's a new key)</p>

<p>But when another user logs in immediately after log out and I attempt to re-intialize an encrypted Realm DB with a new key, like this:</p>

<pre><code>static func intializeRealm() -&gt; Realm! {
    let realmKey = generateSecureRealmKey()
    var configuration = Realm.Configuration()
    configuration.path = RealmDB.getRealmPath()
    configuration.encryptionKey = NSData(bytes: realmKey, length: realmKey.count)
    return try! Realm(configuration: configuration)
  }
</code></pre>

<p>I get this exception: </p>

<pre><code>    *** Terminating app due to uncaught exception 'RLMException', 
         reason: 'Realm at path '****/encrypted.realm' already opened
         with different encryption key'
</code></pre>

<p>It seems that the old <code>configuration cache</code> is still being used (since the filename is the same) even though the realm file has been deleted.</p>

<p>The <a href="https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-2.1.1/Encryption/ViewController.swift" rel="noreferrer">sample encryption app for Realm Swift</a> uses <code>autoreleasepool</code> to get around this, but that doesn't seem feasible for a larger app. Or is it? Would I have to surround all uses of realm with <code>autoreleasepool</code>?</p>