Navigation

Configure & Open a Realm - iOS SDK

A realm is the core data structure used to organize data in Realm Database. For more information, see Realms - iOS SDK.

You can open a realm with the Realm() initializer. If you omit the Realm.Configuration parameter, you will open the default realm. You can use the configuration object to open a realm at a specific file URL, in memory, or with Realm Sync.

You can set the default realm configuration by assigning a new Realm.Configuration instance to the Realm.Configuration.defaultConfiguration class property.

// Open the default realm
let defaultRealm = try! Realm()
// Open the realm with a specific file URL, for example a username
let username = "GordonCole"
var config = Realm.Configuration.defaultConfiguration
config.fileURL!.deleteLastPathComponent()
config.fileURL!.appendPathComponent(username)
config.fileURL!.appendPathExtension("realm")
let realm = try! Realm(configuration: config)

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

You can open a realm entirely in memory, which will not create a .realm file or its associated auxiliary files. Instead the SDK stores objects in memory while the realm is open and discards them immediately when all instances are closed.

Set the inMemoryIdentifier property of the realm configuration. Note that this property cannot be combined with fileURL or syncConfiguration.

// Open the realm with a specific in-memory identifier.
let identifier = "MyRealm"
let config = Realm.Configuration(
inMemoryIdentifier: identifier)
// Open the realm
let realm = try! Realm(configuration: config)
Tip
Operating with Low Memory Constraints

Some applications, such as watchOS apps and iOS app extensions, have tight constraints on their memory footprints. To optimize your data model for low-memory environments, open the realm with a subset of classes.

By default, the iOS SDK automatically adds all Object- and EmbeddedObject-derived classes in your executable to the realm schema. You can control which objects get added by setting the objectTypes property of the Realm.Configuration object.

var config = Realm.Configuration.defaultConfiguration
// Given: `class Task: Object`
// Limit the realm to only the Task object. All other
// Object- and EmbeddedObject-derived classes are not added.
config.objectTypes = [Task.self]
let realm = try! Realm(configuration: config)

You might define properties whose values are initialized using Realm Database APIs. For example:

class SomeSwiftType {
let persons = try! Realm().objects(Person.self)
// ...
}

If this initialization code runs before you set up your Realm configurations, you might get unexpected behavior. For example, if you set a migration block for the default realm configuration in applicationDidFinishLaunching(), but you create an instance of SomeSwiftType before applicationDidFinishLaunching(), you might be accessing your realm before it has been correctly configured.

To avoid such issues, consider doing one of the following:

  • Defer instantiation of any type that eagerly initializes properties using Realm Database APIs until after your app has completed setting up its realm configurations.
  • Define your properties using Swift’s lazy keyword. This allows you to safely instantiate such types at any time during your application’s lifecycle, as long as you do not attempt to access your lazy properties until after your app has set up its realm configurations.
  • Only initialize your properties using Realm APIs that explicitly take in user-defined configurations. You can be sure that the configuration values you are using have been set up properly before they are used to open realms.

By default, iOS 8 and above encrypts app files using NSFileProtection whenever the device is locked. If your app attempts to access a realm while the device is locked, you might see the following error:

open() failed: Operation not permitted

To handle this, downgrade the file protection of the folder containing the Realm files. A less strict protection level like NSFileProtectionCompleteUntilFirstUserAuthentication allows file access even when the device is locked.

Tip

If you reduce iOS file encryption, consider using Realm's built-in encryption to secure your data instead.

This example shows how to apply a less strict protection level to the parent directory of the default realm.

let realm = try! Realm()
// Get the realm file's parent directory
let folderPath = realm.configuration.fileURL!.deletingLastPathComponent().path
// Disable file protection for this directory after the user has unlocked the device once
try! FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication],
ofItemAtPath: folderPath)

Realm may create and delete auxiliary files at any time. Instead of downgrading file protection on the files, apply it to the parent folder. This way, the file protection applies to all relevant files regardless of creation time.

Give Feedback