Realm

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

Realm instances are not thread safe and cannot be shared across threads or dispatch queues. You must
construct a new instance for each thread in which a Realm will be accessed. For dispatch queues, this means
that you must construct a new instance in each block which is dispatched, as a queue is not guaranteed to
run all of its blocks on the same thread.

Declaration

Parameters

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.

Note

The returned Realm is confined to the thread on which it was created.
Because GCD does not guarantee that queues will always use the same
thread, accessing the returned Realm outside the callback block (even if
accessed from callbackQueue) is unsafe.

Return Value

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.

Declaration

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.

Throws

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

Declaration

Swift

publicfuncwrite(_block:(()throws->Void))throws

Parameters

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.

Declaration

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.

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.

Warning

This method may only be called during a write transaction.

Declaration

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

If update is true and an object with the same primary key already exists in this Realm, the existing object
will be overwritten by the newly added one. If update is false then it is instead a non-recoverable error
to add an object with a primary key that is already in use. update must be false for object types which
do not have a 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

@available(*, deprecated, message: "Pass .error, .modified or .all rather than a boolean. .error is equivalent to false and .all is equivalent to true.")publicfuncadd(_object:Object,update:Bool)

Parameters

object

The object to be added to this Realm.

update

If true, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.

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.

Declaration

Swift

@available(*, deprecated, message: "Pass .error, .modified or .all rather than a boolean. .error is equivalent to false and .all is equivalent to true.")publicfuncadd<S>(_objects:S,update:Bool)whereS:Sequence,S.Element:Object

Parameters

objects

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

update

If true, objects that are already in the Realm will be updated instead of added anew.

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

You may only pass true to update if the object has a primary key. If no object exists
in the Realm with the same primary key value, the object is inserted. Otherwise, the
existing object is updated with any changed values.

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 object is being created, all required properties that were not defined with default
values must be given initial values through the value argument. Otherwise, an Objective-C
exception will be thrown.

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.

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.

Warning

This method may only be called during a write transaction.

Declaration

Swift

@available(*, deprecated, message: "Pass .error, .modified or .all rather than a boolean. .error is equivalent to false and .all is equivalent to true.")@discardableResultpublicfunccreate<T>(_type:T.Type,value:Any=[:],update:Bool)->TwhereT:Object

Parameters

type

The type of the object to create.

value

The value used to populate the object.

update

If true, the Realm will try to find an existing copy of the object (with the same primary
key), and update it. Otherwise, the object will be added.

Return Value

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.

Declaration

Parameters

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.

Return Value

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.

Return Value

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.

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. This method
may not be called on a read-only Realm.

Declaration

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

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.

Declaration

Returns the computed privileges which the current user has for this Realm.

This combines all privileges granted on the Realm by all Roles which the
current User is a member of into the final privileges which will be
enforced by the server.

The privilege calculation is done locally using cached data, and inherently
may be stale. It is possible that this method may indicate that an
operation is permitted but the server will still reject it if permission is
revoked before the changes have been integrated on the server.

Non-synchronized and fully-synchronized Realms always have permission to
perform all operations.

Declaration

Return Value

Returns the computed privileges which the current user has for the given object.

This combines all privileges granted on the object by all Roles which the
current User is a member of into the final privileges which will be
enforced by the server.

The privilege calculation is done locally using cached data, and inherently
may be stale. It is possible that this method may indicate that an
operation is permitted but the server will still reject it if permission is
revoked before the changes have been integrated on the server.

Non-synchronized and fully-synchronized Realms always have permission to
perform all operations.

The object must be a valid object managed by this Realm. Passing in an
invalidated object, an unmanaged object, or an object managed by a
different Realm will throw an exception.

Parameters

Return Value

Returns the computed privileges which the current user has for the given class.

This combines all privileges granted on the class by all Roles which the
current User is a member of into the final privileges which will be
enforced by the server.

The privilege calculation is done locally using cached data, and inherently
may be stale. It is possible that this method may indicate that an
operation is permitted but the server will still reject it if permission is
revoked before the changes have been integrated on the server.

Non-synchronized and fully-synchronized Realms always have permission to
perform all operations.

Parameters

Return Value

Returns the computed privileges which the current user has for the named class.

This combines all privileges granted on the class by all Roles which the
current User is a member of into the final privileges which will be
enforced by the server.

The privilege calculation is done locally using cached data, and inherently
may be stale. It is possible that this method may indicate that an
operation is permitted but the server will still reject it if permission is
revoked before the changes have been integrated on the server.

Non-synchronized and fully-synchronized Realms always have permission to
perform all operations.

Declaration

Returns this list of the query-based sync subscriptions made for this Realm.

This list includes all subscriptions which are currently in the states
.pending, .created, and .error. Newly created subscriptions which are
still in the .creating state are not included, and calling this
immediately after calling Results.subscribe() will typically not include
that subscription. Similarly, because unsubscription happens asynchronously,
this may continue to include subscriptions after
SyncSubscription.unsubscribe() is called on them.

Requires

This must only be called on a Realm using query-based sync.

Declaration

Subscriptions are created asynchronously, so calling this immediately after
calling Results.subscribe(named:)will typically returnnil. Only
subscriptions which are currently in the states.pending,.created,
and.error` can be retrieved with this method.

Requires

This must only be called on a Realm using query-based sync.

Declaration

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.