Realm
public struct 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.
-
The
Configurationvalue that was used to create theRealminstance.Declaration
Swift
public var configuration: Configuration { get } -
Indicates if the Realm contains any objects.
Declaration
Swift
public var isEmpty: Bool { get }
-
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 theRealm.Configuration.defaultConfigurationproperty to a new value.Throws
AnNSErrorif the Realm could not be initialized.Declaration
Swift
public init() throws -
Obtains a
Realminstance with the given configuration.Throws
An
NSErrorif the Realm could not be initialized.Declaration
Swift
public init(configuration: Configuration) throwsParameters
configurationA configuration value to use when creating the Realm.
-
Obtains a
Realminstance persisted at a specified file URL.Throws
An
NSErrorif the Realm could not be initialized.Declaration
Swift
public init(fileURL: URL) throwsParameters
fileURLThe local URL of the file the Realm should be saved at.
-
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.Declaration
Swift
@discardableResult public static func asyncOpen(configuration: Realm.Configuration = .defaultConfiguration, callbackQueue: DispatchQueue = .main, callback: @escaping (Realm?, Swift.Error?) -> Void) -> AsyncOpenTaskParameters
configurationA configuration object to use when opening the Realm.
callbackQueueThe dispatch queue on which the callback should be run.
callbackA callback block. If the Realm was successfully opened, an it will be passed in as an argument. Otherwise, a
Swift.Errordescribing 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.
-
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 moreDeclaration
Swift
public struct AsyncOpenTask
-
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
writefromRealminstances 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,
writeupdates theRealminstance to the latest Realm version, as ifrefresh()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.
Throws
An
NSErrorif the transaction could not be completed successfully. Ifblockthrows, the function throws the propagatedErrorTypeinstead.Declaration
Swift
public func write(withoutNotifying tokens: [NotificationToken] = [], _ block: (() throws -> Void)) throwsParameters
tokensAn 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.
blockThe block containing actions to perform.
-
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
beginWritefromRealminstances 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,
beginWriteupdates theRealminstance to the latest Realm version, as ifrefresh()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
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
Realminstance are called synchronously. Notification blocks forRealminstances 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
NSErrorif 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] = []) throwsParameters
tokensAn 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
oldObjectandnewObjectwill returntrueforisInvalidated, but re-running the query which providedoldObjectwill 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
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 }
-
What to do when an object being added to or created in a Realm has a primary key that already exists.
See moreDeclaration
Swift
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
UpdatePolicyselected. The update policy must be.errorfor objects with no primary key.Adding an object to a Realm will also add all child relationships referenced by that object (via
ObjectandList<Object>properties). Those objects must also be valid objects to add to this Realm, and the value of theupdate: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
isInvalidatedistrue) 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
objectThe object to be added to this Realm.
updateWhat to do if an object with the same primary key alredy exists. Must be
.errorfor objects without a primary key. -
Adds all the objects in a collection into the Realm.
See
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 : ObjectParameters
objectsA sequence which contains objects to be added to the Realm.
updateHow to handle objects in the collection with a primary key that alredy exists in this Realm. Must be
.errorfor object types without a primary key.updateHow to handle objects in the collection with a primary key that alredy exists in this Realm. Must be
.errorfor object types without a primary key. -
Creates a Realm object with a given value, adding it to the Realm and returning it.
The
valueargument can be a Realm object, a key-value coding compliant object, an array or dictionary returned from the methods inNSJSONSerialization, or anArraycontaining one element for each managed property. Do not pass in aLinkingObjectsinstance, either by itself or as a member of a collection. If thevalueargument 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
.modifiedor.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
valueusing key-value coding. If thevalueargument does not respond tovalue(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 usingNSNullas the updated value, or (if you are passing in an instance of anObjectsubclass) setting the corresponding property onvalueto nil.Warning
This method may only be called during a write transaction.
Declaration
Swift
@discardableResult public func create<T>(_ type: T.Type, value: Any = [:], update: UpdatePolicy = .error) -> T where T : ObjectParameters
typeThe type of the object to create.
valueThe value used to populate the object.
updateWhat to do if an object with the same primary key alredy exists. Must be
.errorfor object types without a primary key.Return Value
The newly created object.
-
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: Object)Parameters
objectThe object to be deleted.
-
Deletes zero or more objects from the Realm.
Do not pass in a slice to a
Resultsor any other auto-updating Realm collection type (for example, the type returned by the Swiftsuffix(_:)standard library method). Instead, make a copy of the objects to delete usingArray(), 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 : ObjectParameters
objectsThe objects to be deleted. This can be a
List<Object>,Results<Object>, or any other SwiftSequencewhose elements areObjects (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()
-
Returns all objects of the given type stored in the Realm.
Declaration
Parameters
typeThe type of the objects to be returned.
Return Value
A
Resultscontaining 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 : ObjectParameters
typeThe type of the object to be returned.
keyThe primary key of the desired object.
Return Value
An object of type
type, ornilif no instance with the given primary key exists.
-
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) -> NotificationTokenParameters
blockA 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.
-
Set this property to
trueto 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 tofalse, you must manually callrefresh()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 ifautorefreshis set totrue.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
autorefreshon aRealmwithout any strong references to it will not have any effect, andautorefreshwill revert back totruethe next time the Realm is created. This is normally irrelevant as it means that there is nothing to refresh (as managedObjects,Lists, andResultshave strong references to theRealmthat manages them), but it means that settingautorefresh = falseinapplication(_: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.
Declaration
Swift
@discardableResult public func refresh() -> BoolReturn Value
Whether there were any updates for the Realm. Note that
truemay be returned even if no data actually changed.
-
Invalidates all
Objects,Results,LinkingObjects, andLists 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,ResultsandListinstances obtained from thisRealminstance on the current thread are invalidated.Objects andArrays cannot be used.Resultswill 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
Swift
public func invalidate()
-
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
NSErrorif the copy could not be written.Declaration
Swift
public func writeCopy(toFile fileURL: URL, encryptionKey: Data? = nil) throwsParameters
fileURLLocal URL to save the Realm to.
encryptionKeyOptional 64-byte encryption key to encrypt the new file with.
-
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
-
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.
See morelet realm: Realm? do { realm = try Realm() } catch Realm.Error.incompatibleLockFile { print("Realm Browser app may be attached to Realm on device?") }Declaration
Swift
public struct Error
-
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) throwsParameters
configurationThe Realm configuration used to open and migrate the Realm.
-
Returns whether two
Realminstances are equal.Declaration
Swift
public static func == (lhs: Realm, rhs: Realm) -> Bool
-
A notification indicating that changes were made to a Realm.
See moreDeclaration
Swift
public enum Notification : String
-
A
Configurationinstance describes the different options used to create an instance of a Realm.Configurationinstances are just plain Swift structs. UnlikeRealms andObjects, they can be freely shared between threads as long as you do not mutate them.Creating configuration values for class subsets (by setting the
See moreobjectClassesproperty) 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
Swift
public struct Configuration
-
Get the SyncSession used by this Realm. Will be nil if this is not a synchronized Realm.
Declaration
Swift
public var syncSession: SyncSession? { get }
-
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
Swift
public func getPrivileges() -> RealmPrivilegesReturn Value
The privileges which the current user has for the current Realm.
-
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.
Declaration
Swift
public func getPrivileges(_ object: Object) -> ObjectPrivilegesParameters
objectA managed object to get the privileges for.
Return Value
The privileges which the current user has for the given object.
-
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.
Declaration
Swift
public func getPrivileges<T>(_ cls: T.Type) -> ClassPrivileges where T : ObjectParameters
clsAn Object subclass to get the privileges for.
Return Value
The privileges which the current user has for the given class.
-
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
Swift
public func getPrivileges(forClassNamed className: String) -> ClassPrivilegesParameters
classNameThe name of an Object subclass to get the privileges for.
Return Value
The privileges which the current user has for the named class.
-
Returns the class-wide permissions for the given class.
Requires
This must only be called on a Realm using query-based sync.Declaration
Swift
public func permissions<T>(forType cls: T.Type) -> List<Permission> where T : ObjectParameters
clsAn Object subclass to get the permissions for.
Return Value
The class-wide permissions for the given class.
-
Returns the class-wide permissions for the named class.
Requires
className must name a class in this Realm’s schema.Requires
This must only be called on a Realm using query-based sync.Declaration
Swift
public func permissions(forClassNamed className: String) -> List<Permission>Parameters
clsThe name of an Object subclass to get the permissions for.
Return Value
The class-wide permissions for the named class.
-
Returns the Realm-wide permissions.
Requires
This must only be called on a Realm using query-based sync.Declaration
Swift
public var permissions: List<Permission> { get }
-
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.creatingstate are not included, and calling this immediately after callingResults.subscribe()will typically not include that subscription. Similarly, because unsubscription happens asynchronously, this may continue to include subscriptions afterSyncSubscription.unsubscribe()is called on them.Requires
This must only be called on a Realm using query-based sync.Declaration
Swift
public func subscriptions() -> Results<SyncSubscription> -
Returns the named query-based sync subscription, if it exists.
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
Swift
public func subscription(named: String) -> SyncSubscription?
-
Returns the same object as the one referenced when the
ThreadSafeReferencewas first created, but resolved for the current Realm for this thread. Returnsnilif this object was deleted after the reference was created.Warning
A
ThreadSafeReferenceobject must be resolved at most once. Failing to resolve aThreadSafeReferencewill 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 : ThreadConfinedParameters
referenceThe thread-safe reference to the thread-confined object to resolve in this Realm.
View on GitHub
Install in Dash
Realm Structure Reference