Navigation

Open and Close a Realm

Open a Synced Realm

To open a synced realm, call asyncOpen, passing in the user’s Configuration object, which includes the partition name. The following code demonstrates this:

let user = app.currentUser()
let partitionValue = "myPartition"

Realm.asyncOpen(configuration: user!.configuration(partitionValue: partitionValue)) { realm, error in
   guard let realm = realm else {
      // handle error
      return
   }
   // Realm successfully opened
}

In the above example, the code shows how to open the realm asynchronously by using asyncOpen. You can also open a realm synchronously by using one of the Realm() initializers, but this may lead to temporary data inconsistencies while the remote data is downloaded, and is generally not recommended.

let realm = try! Realm(configuration: user!.configuration(partitionValue: partitionValue))

Open a Local (Non-Synced) Realm

When opening a local (non-synced) realm, you pass a custom Configuration object that must not contain a SyncConfiguration object. The following example uses the fileURL and readOnly properties to open a readonly local realm with a specific file location:

let config = Realm.Configuration(
   fileURL: Bundle.main.url(forResource: "MyBundledData", withExtension: "realm"),
   readOnly: true)

// Open the Realm with the configuration
let realm = try! Realm(configuration: config)

Close a Realm

There is no need to manually close a realm in Swift. When a realm goes out of scope and is removed from memory due to ARC, the realm is closed.

←   Realms Realm Objects  →