Realm

@frozen
public struct Realm
extension Realm: Equatable

A Realm instance (also referred to as “a Realm”) represents a Realm database.

Realms can either be stored on disk (see init(path:)) or in memory (see Configuration).

Realm instances are cached internally, and constructing equivalent Realm objects (for example, by using the same path or identifier) produces limited overhead.

If you specifically want to ensure a Realm instance is destroyed (for example, if you wish to open a Realm, check some property, and then possibly delete the Realm file and re-open it), place the code which uses the Realm within an autoreleasepool {} and ensure you have no other strong references to it.

Warning

Non-frozen RLMRealm instances are thread-confined and cannot be shared across threads or dispatch queues. Trying to do so will cause an exception to be thrown. You must obtain an instance of RLMRealm on each thread or queue you want to interact with the Realm on. Realms can be confined to a dispatch queue rather than the thread they are opened on by explicitly passing in the queue when obtaining the RLMRealm instance. If this is not done, trying to use the same instance in multiple blocks dispatch to the same queue may fail as queues are not always run on the same thread.

Properties

Initializers

  • Obtains an instance of the default Realm.

    The default Realm is persisted as default.realm under the Documents directory of your Application on iOS, and in your application’s Application Support directory on OS X.

    The default Realm is created using the default Configuration, which can be changed by setting the Realm.Configuration.defaultConfiguration property to a new value.

    Throws

    An NSError if the Realm could not be initialized.

    Declaration

    Swift

    public init(queue: DispatchQueue? = nil) throws

    Parameters

    queue

    An optional dispatch queue to confine the Realm to. If given, this Realm instance can be used from within blocks dispatched to the given queue rather than on the current thread.

  • Obtains a Realm instance with the given configuration.

    Throws

    An NSError if the Realm could not be initialized.

    Declaration

    Swift

    public init(configuration: Configuration, queue: DispatchQueue? = nil) throws

    Parameters

    configuration

    A configuration value to use when creating the Realm.

    queue

    An optional dispatch queue to confine the Realm to. If given, this Realm instance can be used from within blocks dispatched to the given queue rather than on the current thread.

  • Obtains a Realm instance persisted at a specified file URL.

    Throws

    An NSError if the Realm could not be initialized.

    Declaration

    Swift

    public init(fileURL: URL) throws

    Parameters

    fileURL

    The local URL of the file the Realm should be saved at.

Async

  • Asynchronously open a Realm and deliver it to a block on the given queue.

    Opening a Realm asynchronously will perform all work needed to get the Realm to a usable state (such as running potentially time-consuming migrations) on a background thread before dispatching to the given queue. In addition, synchronized Realms wait for all remote content available at the time the operation began to be downloaded and available locally.

    The Realm passed to the callback function is confined to the callback queue as if Realm(configuration:queue:) was used.

    Declaration

    Swift

    @discardableResult
    public static func asyncOpen(configuration: Realm.Configuration = .defaultConfiguration,
                                 callbackQueue: DispatchQueue = .main,
                                 callback: @escaping (Result<Realm, Swift.Error>) -> Void) -> AsyncOpenTask

    Parameters

    configuration

    A configuration object to use when opening the Realm.

    callbackQueue

    The dispatch queue on which the callback should be run.

    callback

    A callback block. If the Realm was successfully opened, an it will be passed in as an argument. Otherwise, a Swift.Error describing what went wrong will be passed to the block instead.

    Return Value

    A task object which can be used to observe or cancel the async open.

  • Asynchronously open a Realm and deliver it to a block on the given queue.

    Opening a Realm asynchronously will perform all work needed to get the Realm to a usable state (such as running potentially time-consuming migrations) on a background thread before dispatching to the given queue. In addition, synchronized Realms wait for all remote content available at the time the operation began to be downloaded and available locally.

    The Realm passed to the publisher is confined to the callback queue as if Realm(configuration:queue:) was used.

    Declaration

    Swift

    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
    public static func asyncOpen(configuration: Realm.Configuration = .defaultConfiguration) -> RealmPublishers.AsyncOpenPublisher

    Parameters

    configuration

    A configuration object to use when opening the Realm.

    callbackQueue

    The dispatch queue on which the AsyncOpenTask should be run.

    Return Value

    A publisher. If the Realm was successfully opened, it will be received by the subscribers. Otherwise, a Swift.Error describing what went wrong will be passed upstream instead.

  • A task object which can be used to observe or cancel an async open.

    When a synchronized Realm is opened asynchronously, the latest state of the Realm is downloaded from the server before the completion callback is invoked. This task object can be used to observe the state of the download or to cancel it. This should be used instead of trying to observe the download via the sync session as the sync session itself is created asynchronously, and may not exist yet when Realm.asyncOpen() returns.

    See more

    Declaration

    Swift

    @frozen
    public struct AsyncOpenTask

Transactions

  • Performs actions contained within the given block inside a write transaction.

    If the block throws an error, the transaction will be canceled and any changes made before the error will be rolled back.

    Only one write transaction can be open at a time for each Realm file. Write transactions cannot be nested, and trying to begin a write transaction on a Realm which is already in a write transaction will throw an exception. Calls to write from Realm instances for the same Realm file in other threads or other processes will block until the current write transaction completes or is cancelled.

    Before beginning the write transaction, write updates the Realm instance to the latest Realm version, as if refresh() had been called, and generates notifications if applicable. This has no effect if the Realm was already up to date.

    You can skip notifiying specific notification blocks about the changes made in this write transaction by passing in their associated notification tokens. This is primarily useful when the write transaction is saving changes already made in the UI and you do not want to have the notification block attempt to re-apply the same changes.

    The tokens passed to this function must be for notifications for this Realm which were added on the same thread as the write transaction is being performed on. Notifications for different threads cannot be skipped using this method.

    Warning

    This function is not safe to call from async functions, which should use asyncWrite instead.

    Throws

    An NSError if the transaction could not be completed successfully. If block throws, the function throws the propagated ErrorType instead.

    Declaration

    Swift

    @discardableResult
    public func write<Result>(withoutNotifying tokens: [NotificationToken] = [], _ block: (() throws -> Result)) throws -> Result

    Parameters

    tokens

    An array of notification tokens which were returned from adding callbacks which you do not want to be notified for the changes made in this write transaction.

    block

    The block containing actions to perform.

    Return Value

    The value returned from the block, if any.

  • Begins a write transaction on the Realm.

    Only one write transaction can be open at a time for each Realm file. Write transactions cannot be nested, and trying to begin a write transaction on a Realm which is already in a write transaction will throw an exception. Calls to beginWrite from Realm instances for the same Realm file in other threads or other processes will block until the current write transaction completes or is cancelled.

    Before beginning the write transaction, beginWrite updates the Realm instance to the latest Realm version, as if refresh() had been called, and generates notifications if applicable. This has no effect if the Realm was already up to date.

    It is rarely a good idea to have write transactions span multiple cycles of the run loop, but if you do wish to do so you will need to ensure that the Realm participating in the write transaction is kept alive until the write transaction is committed.

    Warning

    This function is not safe to call from async functions, which should use asyncWrite instead.

    Declaration

    Swift

    public func beginWrite()
  • Commits all write operations in the current write transaction, and ends the transaction.

    After saving the changes and completing the write transaction, all notification blocks registered on this specific Realm instance are called synchronously. Notification blocks for Realm instances on other threads and blocks registered for any Realm collection (including those on the current thread) are scheduled to be called synchronously.

    You can skip notifiying specific notification blocks about the changes made in this write transaction by passing in their associated notification tokens. This is primarily useful when the write transaction is saving changes already made in the UI and you do not want to have the notification block attempt to re-apply the same changes.

    The tokens passed to this function must be for notifications for this Realm which were added on the same thread as the write transaction is being performed on. Notifications for different threads cannot be skipped using this method.

    Warning

    This method may only be called during a write transaction.

    Throws

    An NSError if the transaction could not be written due to running out of disk space or other i/o errors.

    Declaration

    Swift

    public func commitWrite(withoutNotifying tokens: [NotificationToken] = []) throws

    Parameters

    tokens

    An array of notification tokens which were returned from adding callbacks which you do not want to be notified for the changes made in this write transaction.

  • Reverts all writes made in the current write transaction and ends the transaction.

    This rolls back all objects in the Realm to the state they were in at the beginning of the write transaction, and then ends the transaction.

    This restores the data for deleted objects, but does not revive invalidated object instances. Any Objects which were added to the Realm will be invalidated rather than becoming unmanaged.

    Given the following code:

    let oldObject = objects(ObjectType).first!
    let newObject = ObjectType()
    
    realm.beginWrite()
    realm.add(newObject)
    realm.delete(oldObject)
    realm.cancelWrite()
    

    Both oldObject and newObject will return true for isInvalidated, but re-running the query which provided oldObject will once again return the valid object.

    KVO observers on any objects which were modified during the transaction will be notified about the change back to their initial values, but no other notifcations are produced by a cancelled write transaction.

    This function is applicable regardless of how a write transaction was started. Notably it can be called from inside a block passed to write or writeAsync.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func cancelWrite()
  • Indicates whether the Realm is currently in a write transaction.

    Warning

    Do not simply check this property and then start a write transaction whenever an object needs to be created, updated, or removed. Doing so might cause a large number of write transactions to be created, degrading performance. Instead, always prefer performing multiple updates during a single transaction.

    Declaration

    Swift

    public var isInWriteTransaction: Bool { get }

Asynchronous Transactions

  • Asynchronously performs actions contained within the given block inside a write transaction. The write transaction is begun asynchronously as if calling beginAsyncWrite, and by default the transaction is committed asynchronously after the block completes. You can also explicitly call commitWrite or cancelWrite from within the block to synchronously commit or cancel the write transaction. Returning without one of these calls is equivalent to calling commitWrite.

    @param block The block containing actions to perform.

    @param completionBlock A block which will be called on the source thread or queue once the commit has either completed or failed with an error.

    @return An id identifying the asynchronous transaction which can be passed to cancelAsyncWrite prior to the block being called to cancel the pending invocation of the block.

    Declaration

    Swift

    @discardableResult
    public func writeAsync(_ block: @escaping () -> Void, onComplete: ((Swift.Error?) -> Void)? = nil) -> AsyncTransactionId
  • Begins an asynchronous write transaction. This function asynchronously begins a write transaction on a background thread, and then invokes the block on the original thread or queue once the transaction has begun. Unlike beginWrite, this does not block the calling thread if another thread is current inside a write transaction, and will always return immediately. Multiple calls to this function (or the other functions which perform asynchronous write transactions) will queue the blocks to be called in the same order as they were queued. This includes calls from inside a write transaction block, which unlike with synchronous transactions are allowed.

    @param asyncWriteBlock The block containing actions to perform inside the write transaction. asyncWriteBlock should end by calling commitAsyncWrite or commitWrite. Returning without one of these calls is equivalent to calling cancelAsyncWrite.

    @return An id identifying the asynchronous transaction which can be passed to cancelAsyncWrite prior to the block being called to cancel the pending invocation of the block.

    Declaration

    Swift

    @discardableResult
    public func beginAsyncWrite(_ asyncWriteBlock: @escaping () -> Void) -> AsyncTransactionId
  • Asynchronously commits a write transaction. The call returns immediately allowing the caller to proceed while the I/O is performed on a dedicated background thread. This can be used regardless of if the write transaction was begun with beginWrite or beginAsyncWrite.

    @param onComplete A block which will be called on the source thread or queue once the commit has either completed or failed with an error.

    @param allowGrouping If true, multiple sequential calls to commitAsyncWrite may be batched together and persisted to stable storage in one group. This improves write performance, particularly when the individual transactions being batched are small. In the event of a crash or power failure, either all of the grouped transactions will be lost or none will, rather than the usual guarantee that data has been persisted as soon as a call to commit has returned.

    @return An id identifying the asynchronous transaction commit can be passed to cancelAsyncWrite prior to the completion block being called to cancel the pending invocation of the block. Note that this does not cancel the commit itself.

    Declaration

    Swift

    @discardableResult
    public func commitAsyncWrite(allowGrouping: Bool = false, _ onComplete: ((Swift.Error?) -> Void)? = nil) -> AsyncTransactionId
  • Cancels a queued block for an asynchronous transaction. This can cancel a block passed to either an asynchronous begin or an asynchronous commit. Canceling a begin cancels that transaction entirely, while canceling a commit merely cancels the invocation of the completion callback, and the commit will still happen. Transactions can only be canceled before the block is invoked, and calling cancelAsyncWrite from within the block is a no-op.

    @param AsyncTransactionId A transaction id from either beginAsyncWrite or commitAsyncWrite.

    Declaration

    Swift

    public func cancelAsyncWrite(_ asyncTransactionId: AsyncTransactionId) throws
  • Indicates if the Realm is currently performing async write operations. This becomes true following a call to beginAsyncWrite, commitAsyncWrite, or writeAsync, and remains so until all scheduled async write work has completed.

    Warning

    If this is true, closing or invalidating the Realm will block until scheduled work has completed.

    Declaration

    Swift

    public var isPerformingAsynchronousWriteOperations: Bool { get }

Adding and Creating objects

  • What to do when an object being added to or created in a Realm has a primary key that already exists.

    See more

    Declaration

    Swift

    @frozen
    public enum UpdatePolicy : Int
  • Adds an unmanaged object to this Realm.

    If an object with the same primary key already exists in this Realm, it is updated with the property values from this object as specified by the UpdatePolicy selected. The update policy must be .error for objects with no primary key.

    Adding an object to a Realm will also add all child relationships referenced by that object (via Object and List<Object> properties). Those objects must also be valid objects to add to this Realm, and the value of the update: parameter is propagated to those adds.

    The object to be added must either be an unmanaged object or a valid object which is already managed by this Realm. Adding an object already managed by this Realm is a no-op, while adding an object which is managed by another Realm or which has been deleted from any Realm (i.e. one where isInvalidated is true) is an error.

    To copy a managed object from one Realm to another, use create() instead.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func add(_ object: Object, update: UpdatePolicy = .error)

    Parameters

    object

    The object to be added to this Realm.

    update

    What to do if an object with the same primary key already exists. Must be .error for objects without a primary key.

  • Adds all the objects in a collection into the Realm.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func add<S>(_ objects: S, update: UpdatePolicy = .error) where S : Sequence, S.Element : RealmSwiftObject

    Parameters

    objects

    A sequence which contains objects to be added to the Realm.

    update

    How to handle objects in the collection with a primary key that already exists in this Realm. Must be .error for object types without a primary key.

    update

    How to handle objects in the collection with a primary key that already exists in this Realm. Must be .error for object types without a primary key.

  • Creates a Realm object with a given value, adding it to the Realm and returning it.

    The value argument can be a Realm object, a key-value coding compliant object, an array or dictionary returned from the methods in NSJSONSerialization, or an Array containing one element for each managed property. Do not pass in a LinkingObjects instance, either by itself or as a member of a collection. If the value argument is an array, all properties must be present, valid and in the same order as the properties defined in the model.

    If the object type does not have a primary key or no object with the specified primary key already exists, a new object is created in the Realm. If an object already exists in the Realm with the specified primary key and the update policy is .modified or .all, the existing object will be updated and a reference to that object will be returned.

    If the object is being updated, all properties defined in its schema will be set by copying from value using key-value coding. If the value argument does not respond to value(forKey:) for a given property name (or getter name, if defined), that value will remain untouched. Nullable properties on the object can be set to nil by using NSNull as the updated value, or (if you are passing in an instance of an Object subclass) setting the corresponding property on value to nil.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    @discardableResult
    public func create<T>(_ type: T.Type, value: Any = [String: Any](), update: UpdatePolicy = .error) -> T where T : RealmSwiftObject

    Parameters

    type

    The type of the object to create.

    value

    The value used to populate the object.

    update

    What to do if an object with the same primary key already exists. Must be .error for object types without a primary key.

    Return Value

    The newly created object.

Deleting objects

  • Deletes an object from the Realm. Once the object is deleted it is considered invalidated.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func delete(_ object: ObjectBase)

    Parameters

    object

    The object to be deleted.

  • Deletes zero or more objects from the Realm.

    Do not pass in a slice to a Results or any other auto-updating Realm collection type (for example, the type returned by the Swift suffix(_:) standard library method). Instead, make a copy of the objects to delete using Array(), and pass that instead. Directly passing in a view into an auto-updating collection may result in ‘index out of bounds’ exceptions being thrown.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func delete<S>(_ objects: S) where S : Sequence, S.Element : RLMObjectBase

    Parameters

    objects

    The objects to be deleted. This can be a List<Object>, Results<Object>, or any other Swift Sequence whose elements are Objects (subject to the caveats above).

  • Deletes all objects from the Realm.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func deleteAll()

Object Retrieval

  • Returns all objects of the given type stored in the Realm.

    Declaration

    Swift

    public func objects<Element>(_ type: Element.Type) -> Results<Element> where Element : RealmFetchable

    Parameters

    type

    The type of the objects to be returned.

    Return Value

    A Results containing the objects.

  • Retrieves the single instance of a given object type with the given primary key from the Realm.

    This method requires that primaryKey() be overridden on the given object class.

    Declaration

    Swift

    public func object<Element, KeyType>(ofType type: Element.Type, forPrimaryKey key: KeyType) -> Element? where Element : RealmSwiftObject

    Parameters

    type

    The type of the object to be returned.

    key

    The primary key of the desired object.

    Return Value

    An object of type type, or nil if no instance with the given primary key exists.

Notifications

  • Adds a notification handler for changes made to this Realm, and returns a notification token.

    Notification handlers are called after each write transaction is committed, independent of the thread or process.

    Handler blocks are called on the same thread that they were added on, and may only be added on threads which are currently within a run loop. Unless you are specifically creating and running a run loop on a background thread, this will normally only be the main thread.

    Notifications can’t be delivered as long as the run loop is blocked by other activity. When notifications can’t be delivered instantly, multiple notifications may be coalesced.

    You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call invalidate() on the token.

    Declaration

    Swift

    public func observe(_ block: @escaping NotificationBlock) -> NotificationToken

    Parameters

    block

    A block which is called to process Realm notifications. It receives the following parameters: notification: the incoming notification; realm: the Realm for which the notification occurred.

    Return Value

    A token which must be held for as long as you wish to continue receiving change notifications.

Autorefresh and Refresh

  • Set this property to true to automatically update this Realm when changes happen in other threads.

    If set to true (the default), changes made on other threads will be reflected in this Realm on the next cycle of the run loop after the changes are committed. If set to false, you must manually call refresh() on the Realm to update it to get the latest data.

    Note that by default, background threads do not have an active run loop and you will need to manually call refresh() in order to update to the latest version, even if autorefresh is set to true.

    Even with this property enabled, you can still call refresh() at any time to update the Realm before the automatic refresh would occur.

    Notifications are sent when a write transaction is committed whether or not automatic refreshing is enabled.

    Disabling autorefresh on a Realm without any strong references to it will not have any effect, and autorefresh will revert back to true the next time the Realm is created. This is normally irrelevant as it means that there is nothing to refresh (as managed Objects, Lists, and Results have strong references to the Realm that manages them), but it means that setting autorefresh = false in application(_:didFinishLaunchingWithOptions:) and only later storing Realm objects will not work.

    Defaults to true.

    Declaration

    Swift

    public var autorefresh: Bool { get nonmutating set }
  • Updates the Realm and outstanding objects managed by the Realm to point to the most recent data and deliver any applicable notifications.

    By default Realms will automatically refresh in a more efficient way than is possible with this function. This function should be avoided when possible.

    Warning

    This function is not safe to call from async functions, which should use asyncRefresh instead.

    Declaration

    Swift

    @discardableResult
    public func refresh() -> Bool

    Return Value

    Whether there were any updates for the Realm. Note that true may be returned even if no data actually changed.

Frozen Realms

  • Returns if this Realm is frozen.

    Declaration

    Swift

    public var isFrozen: Bool { get }
  • Returns a frozen (immutable) snapshot of this Realm.

    A frozen Realm is an immutable snapshot view of a particular version of a Realm’s data. Unlike normal Realm instances, it does not live-update to reflect writes made to the Realm, and can be accessed from any thread. Writing to a frozen Realm is not allowed, and attempting to begin a write transaction will throw an exception.

    All objects and collections read from a frozen Realm will also be frozen.

    Warning

    Holding onto a frozen Realm for an extended period while performing write transaction on the Realm may result in the Realm file growing to large sizes. See Realm.Configuration.maximumNumberOfActiveVersions for more information.

    Declaration

    Swift

    public func freeze() -> Realm
  • Returns a live (mutable) reference of this Realm.

    All objects and collections read from the returned Realm reference will no longer be frozen. Will return self if called on a Realm that is not already frozen.

    Declaration

    Swift

    public func thaw() -> Realm
  • Returns a frozen (immutable) snapshot of the given object.

    The frozen copy is an immutable object which contains the same data as the given object currently contains, but will not update when writes are made to the containing Realm. Unlike live objects, frozen objects can be accessed from any thread.

    Warning

    Holding onto a frozen object for an extended period while performing write transaction on the Realm may result in the Realm file growing to large sizes. See Realm.Configuration.maximumNumberOfActiveVersions for more information.

    Declaration

    Swift

    public func freeze<T>(_ obj: T) -> T where T : RLMObjectBase
  • Returns a live (mutable) reference of this object.

    This method creates a managed accessor to a live copy of the same frozen object. Will return self if called on an already live object.

    Declaration

    Swift

    public func thaw<T>(_ obj: T) -> T? where T : RLMObjectBase
  • Returns a frozen (immutable) snapshot of the given collection.

    The frozen copy is an immutable collection which contains the same data as the given collection currently contains, but will not update when writes are made to the containing Realm. Unlike live collections, frozen collections can be accessed from any thread.

    Warning

    This method cannot be called during a write transaction, or when the Realm is read-only.

    Warning

    Holding onto a frozen collection for an extended period while performing write transaction on the Realm may result in the Realm file growing to large sizes. See Realm.Configuration.maximumNumberOfActiveVersions for more information.

    Declaration

    Swift

    public func freeze<Collection>(_ collection: Collection) -> Collection where Collection : RealmCollection

Invalidation

  • Invalidates all Objects, Results, LinkingObjects, and Lists managed by the Realm.

    A Realm holds a read lock on the version of the data accessed by it, so that changes made to the Realm on different threads do not modify or delete the data seen by this Realm. Calling this method releases the read lock, allowing the space used on disk to be reused by later write transactions rather than growing the file. This method should be called before performing long blocking operations on a background thread on which you previously read data from the Realm which you no longer need.

    All Object, Results and List instances obtained from this Realm instance on the current thread are invalidated. Objects and Arrays cannot be used. Results will become empty. The Realm itself remains valid, and a new read transaction is implicitly begun the next time data is read from the Realm.

    Calling this method multiple times in a row without reading any data from the Realm, or before ever reading any data from the Realm, is a no-op.

    Declaration

    Swift

    public func invalidate()

File Management

  • Writes a compacted and optionally encrypted copy of the Realm to the given local URL.

    The destination file cannot already exist.

    Note that if this method is called from within a write transaction, the current data is written, not the data from the point when the previous write transaction was committed.

    Throws

    An NSError if the copy could not be written.

    Declaration

    Swift

    public func writeCopy(toFile fileURL: URL, encryptionKey: Data? = nil) throws

    Parameters

    fileURL

    Local URL to save the Realm to.

    encryptionKey

    Optional 64-byte encryption key to encrypt the new file with.

  • Writes a copy of the Realm to a given location specified by a given configuration.

    If the configuration supplied is derived from a User then this Realm will be copied with sync functionality enabled.

    The destination file cannot already exist.

    Throws

    An NSError if the copy could not be written.

    Declaration

    Swift

    public func writeCopy(configuration: Realm.Configuration) throws

    Parameters

    configuration

    A Realm Configuration.

  • Checks if the Realm file for the given configuration exists locally on disk.

    For non-synchronized, non-in-memory Realms, this is equivalent to FileManager.default.fileExists(atPath:). For synchronized Realms, it takes care of computing the actual path on disk based on the server, virtual path, and user as is done when opening the Realm.

    @param config A Realm configuration to check the existence of. @return true if the Realm file for the given configuration exists on disk, false otherwise.

    Declaration

    Swift

    public static func fileExists(for config: Configuration) -> Bool
  • Deletes the local Realm file and associated temporary files for the given configuration.

    This deletes the “.realm”, “.note” and “.management” files which would be created by opening the Realm with the given configuration. It does not delete the “.lock” file (which contains no persisted data and is recreated from scratch every time the Realm file is opened).

    The Realm must not be currently open on any thread or in another process. If it is, this will throw the error .alreadyOpen. Attempting to open the Realm on another thread while the deletion is happening will block, and then create a new Realm and open that afterwards.

    If the Realm already does not exist this will return false.

    @param config A Realm configuration identifying the Realm to be deleted. @return true if any files were deleted, false otherwise.

    Declaration

    Swift

    public static func deleteFiles(for config: Configuration) throws -> Bool

Realm

  • A publisher that emits Void each time the object changes.

    Despite the name, this actually emits after the collection has changed.

    Declaration

    Swift

    public var objectWillChange: RealmPublishers.RealmWillChange { get }
  • Struct that describes the error codes within the Realm error domain. The values can be used to catch a variety of recoverable errors, especially those happening when initializing a Realm instance.

    let realm: Realm?
    do {
        realm = try Realm()
    } catch Realm.Error.incompatibleLockFile {
        print("Realm Browser app may be attached to Realm on device?")
    }
    

    Declaration

    Swift

    public typealias Error = RLMError
  • Declaration

    Swift

    extension Realm.Error
    extension Realm.Error: @retroactive Equatable

Equatable

  • Get the event context for the Realm. Will be nil unless an EventConfiguration was set while opening the Realm.

    Declaration

    Swift

    public var events: Events? { get }
  • Performs the given Realm configuration’s migration block on a Realm at the given path.

    This method is called automatically when opening a Realm for the first time and does not need to be called explicitly. You can choose to call this method to control exactly when and how migrations are performed.

    Declaration

    Swift

    public static func performMigration(for configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration) throws

    Parameters

    configuration

    The Realm configuration used to open and migrate the Realm.

Sync Subscriptions

  • Returns an instance of SyncSubscriptionSet, representing the active subscriptions for this realm, which can be used to add/remove/update and search flexible sync subscriptions. Getting the subscriptions from a local or partition-based configured realm will thrown an exception.

    Warning

    This feature is currently in beta and its API is subject to change.

    Declaration

    Swift

    public var subscriptions: SyncSubscriptionSet { get }

    Return Value

    A SyncSubscriptionSet.

Asymmetric Sync

  • Creates an Asymmetric object, which will be synced unidirectionally and cannot be queried locally. Only objects which inherit from AsymmetricObject can be created using this method.

    Objects created using this method will not be added to the Realm.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func create<T>(_ type: T.Type, value: Any = [String: Any]()) where T : RealmSwiftAsymmetricObject

    Parameters

    type

    The type of the object to create.

    value

    The value used to populate the object.

Equatable

  • Returns whether two Realm instances are equal.

    Declaration

    Swift

    public static func == (lhs: Realm, rhs: Realm) -> Bool

Notifications

  • A notification indicating that changes were made to a Realm.

    See more

    Declaration

    Swift

    @frozen
    public enum Notification : String
  • Options for when to download all data from the server before opening a synchronized Realm.

    See more

    Declaration

    Swift

    @frozen
    public enum OpenBehavior : Sendable
  • Obtains a Realm instance with the given configuration, possibly asynchronously. By default this simply returns the Realm instance exactly as if the synchronous initializer was used. It optionally can instead open the Realm asynchronously, performing all work needed to get the Realm to a usable state on a background thread. For local Realms, this means that migrations will be run in the background, and for synchronized Realms all data will be downloaded from the server before the Realm is returned.

    Throws

    An NSError if the Realm could not be initialized.

    Declaration

    Swift

    @MainActor
    public init(configuration: Realm.Configuration = .defaultConfiguration,
                downloadBeforeOpen: OpenBehavior = .never) async throws

    Parameters

    configuration

    A configuration object to use when opening the Realm.

    downloadBeforeOpen

    When opening the Realm should first download all data from the server.

    Return Value

    An open Realm.

  • Asynchronously obtains a Realm instance isolated to the given Actor.

    Opening a Realm with an actor isolates the Realm to that actor. Rather than being confined to the specific thread which the Realm was opened on, the Realm can instead only be used from within that actor or functions isolated to that actor. Isolating a Realm to an actor also enables using asyncWrite and asyncRefresh.

    All initialization work to prepare the Realm for work, such as creating, migrating, or compacting the file on disk, and waiting for synchronized Realms to download the latest data from the server is done on a background thread and does not block the calling executor.

    When using actor-isolated Realms, enabling struct concurrency checking (SWIFT_STRICT_CONCURRENCY=complete in Xcode) and runtime data race detection (by passing -Xfrontend -enable-actor-data-race-checks to the compiler) is strongly recommended.

    Throws

    An NSError if the Realm could not be initialized. CancellationError if the task is cancelled.

    Declaration

    Swift

    public init<A: Actor>(configuration: Realm.Configuration = .defaultConfiguration,
                          actor: A,
                          downloadBeforeOpen: OpenBehavior = .never) async throws

    Parameters

    configuration

    A configuration object to use when opening the Realm.

    actor

    The actor to confine this Realm to. The actor can be either a local actor or a global actor. The calling function does not need to be isolated to the actor passed in, but if it is not it will not be able to use the returned Realm.

    downloadBeforeOpen

    When opening the Realm should first download all data from the server.

    Return Value

    An open Realm.

  • Asynchronously obtains a Realm instance isolated to the current Actor.

    Opening a Realm with an actor isolates the Realm to that actor. Rather than being confined to the specific thread which the Realm was opened on, the Realm can instead only be used from within that actor or functions isolated to that actor. Isolating a Realm to an actor also enables using asyncWrite and asyncRefresh.

    All initialization work to prepare the Realm for work, such as creating, migrating, or compacting the file on disk, and waiting for synchronized Realms to download the latest data from the server is done on a background thread and does not block the calling executor.

    Throws

    An NSError if the Realm could not be initialized. CancellationError if the task is cancelled.

    Declaration

    Swift

    public static func open(configuration: Realm.Configuration = .defaultConfiguration,
                            _isolation actor: isolated any Actor = #isolation,
                            downloadBeforeOpen: OpenBehavior = .never) async throws -> Realm

    Parameters

    configuration

    A configuration object to use when opening the Realm.

    downloadBeforeOpen

    When opening the Realm should first download all data from the server.

    Return Value

    An open Realm.

  • Performs actions contained within the given block inside a write transaction.

    This function differs from synchronous write in that it suspends the calling task while waiting for its turn to write rather than blocking the thread. In addition, the actual i/o to write data to disk is done by a background worker thread. For small writes, using this function on the main thread may block the main thread for less time than manually dispatching the write to a background thread.

    If the block throws an error, the transaction will be canceled and any changes made before the error will be rolled back.

    Only one write transaction can be open at a time for each Realm file. Write transactions cannot be nested, and trying to begin a write transaction on a Realm which is already in a write transaction will throw an exception. Calls to write from Realm instances for the same Realm file in other threads or other processes will block until the current write transaction completes or is cancelled.

    Before beginning the write transaction, asyncWrite updates the Realm instance to the latest Realm version, as if asyncRefresh() had been called, and generates notifications if applicable. This has no effect if the Realm was already up to date.

    You can skip notifying specific notification blocks about the changes made in this write transaction by passing in their associated notification tokens. This is primarily useful when the write transaction is saving changes already made in the UI and you do not want to have the notification block attempt to re-apply the same changes.

    The tokens passed to this function must be for notifications for this Realm which were added on the same actor as the write transaction is being performed on. Notifications for different threads cannot be skipped using this method.

    Throws

    An NSError if the transaction could not be completed successfully. CancellationError if the task is cancelled. If block throws, the function throws the propagated ErrorType instead.

  • Updates the Realm and outstanding objects managed by the Realm to point to the most recent data and deliver any applicable notifications.

    This function should be used instead of synchronous refresh in async functions, as it suspends the calling task (if required) rather than blocking.

    Warning

    This function is only supported for main thread and actor-isolated Realms.
  • Performs actions contained within the given block inside a write transaction.

    This function differs from synchronous write in that it suspends the calling task while waiting for its turn to write rather than blocking the thread. In addition, the actual i/o to write data to disk is done by a background worker thread. For small writes, using this function on the main thread may block the main thread for less time than manually dispatching the write to a background thread.

    If the block throws an error, the transaction will be canceled and any changes made before the error will be rolled back.

    Only one write transaction can be open at a time for each Realm file. Write transactions cannot be nested, and trying to begin a write transaction on a Realm which is already in a write transaction will throw an exception. Calls to write from Realm instances for the same Realm file in other threads or other processes will block until the current write transaction completes or is cancelled.

    Before beginning the write transaction, asyncWrite updates the Realm instance to the latest Realm version, as if asyncRefresh() had been called, and generates notifications if applicable. This has no effect if the Realm was already up to date.

    You can skip notifying specific notification blocks about the changes made in this write transaction by passing in their associated notification tokens. This is primarily useful when the write transaction is saving changes already made in the UI and you do not want to have the notification block attempt to re-apply the same changes.

    The tokens passed to this function must be for notifications for this Realm which were added on the same actor as the write transaction is being performed on. Notifications for different threads cannot be skipped using this method.

    Throws

    An NSError if the transaction could not be completed successfully. CancellationError if the task is cancelled. If block throws, the function throws the propagated ErrorType instead.

    Declaration

    Swift

    @discardableResult
    public func asyncWrite<Result>(_isolation actor: isolated any Actor = #isolation, _ block: (() throws -> Result)) async throws -> Result

    Parameters

    tokens

    An array of notification tokens which were returned from adding callbacks which you do not want to be notified for the changes made in this write transaction.

    block

    The block containing actions to perform.

    Return Value

    The value returned from the block, if any.

  • Updates the Realm and outstanding objects managed by the Realm to point to the most recent data and deliver any applicable notifications.

    This function should be used instead of synchronous refresh in async functions, as it suspends the calling task (if required) rather than blocking.

    Warning

    This function is only supported for main thread and actor-isolated Realms.

    Declaration

    Swift

    @discardableResult
    public func asyncRefresh(_isolation: isolated any Actor = #isolation) async -> Bool

    Return Value

    Whether there were any updates for the Realm. Note that true may be returned even if no data actually changed.

  • A Configuration instance describes the different options used to create an instance of a Realm.

    Configuration instances are just plain Swift structs. Unlike Realms and Objects, they can be freely shared between threads as long as you do not mutate them.

    Creating configuration values for class subsets (by setting the objectClasses property) can be expensive. Because of this, you will normally want to cache and reuse a single configuration value for each distinct configuration rather than creating a new value each time you open a Realm.

    See more

    Declaration

    Swift

    @frozen
    public struct Configuration : Sendable
    extension Realm.Configuration: CustomStringConvertible
    extension Realm.Configuration: Equatable
  • Get the SyncSession used by this Realm. Will be nil if this is not a synchronized Realm.

    Declaration

    Swift

    public var syncSession: SyncSession? { get }

Thread Safe Reference

  • Returns the same object as the one referenced when the ThreadSafeReference was first created, but resolved for the current Realm for this thread. Returns nil if this object was deleted after the reference was created.

    Warning

    A ThreadSafeReference object must be resolved at most once. Failing to resolve a ThreadSafeReference will result in the source version of the Realm being pinned until the reference is deallocated. An exception will be thrown if a reference is resolved more than once.

    Warning

    Cannot call within a write transaction.

    Note

    Will refresh this Realm if the source Realm was at a later version than this one.

    See

    ThreadSafeReference(to:)

    Declaration

    Swift

    public func resolve<Confined>(_ reference: ThreadSafeReference<Confined>) -> Confined? where Confined : ThreadConfined

    Parameters

    reference

    The thread-safe reference to the thread-confined object to resolve in this Realm.