RLMRealm
Objective-C
@interface RLMRealm : NSObject
Swift
@_nonSendable(_assumed) class RLMRealm : NSObject
An RLMRealm
instance (also referred to as “a Realm”) represents a Realm
database.
Realms can either be stored on disk (see +[RLMRealm realmWithURL:]
) or in
memory (see RLMRealmConfiguration
).
RLMRealm
instances are cached internally, and constructing equivalent RLMRealm
objects (for example, by using the same path or identifier) multiple times on a single thread
within a single iteration of the run loop will normally return the same
RLMRealm
object.
If you specifically want to ensure an RLMRealm
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-frozenRLMRealm
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 call this method on each thread you want to
interact with the Realm on. For dispatch queues, this means that you must call
it in each block which is dispatched, as a queue is not guaranteed to run all
of its blocks on the same thread.
-
Obtains an instance of the default Realm.
The default Realm is used by the
RLMObject
class methods which do not take anRLMRealm
parameter, but is otherwise not special. The default Realm is persisted as default.realm under the Documents directory of your Application on iOS, in your application’s Application Support directory on macOS, and in the Cache directory on tvOS.The default Realm is created using the default
RLMRealmConfiguration
, which can be changed via+[RLMRealmConfiguration setDefaultConfiguration:]
.Declaration
Objective-C
+ (nonnull instancetype)defaultRealm;
Swift
class func `default`() -> Self
Return Value
The default
RLMRealm
instance for the current thread. -
Obtains an instance of the default Realm bound to the given queue.
Rather than being confined to the thread they are opened on, queue-bound RLMRealms are confined to the given queue. They can be accessed from any thread as long as it is from within a block dispatch to the queue, and notifications will be delivered to the queue instead of a thread’s run loop.
Realms can only be confined to a serial queue. Queue-confined RLMRealm instances can be obtained when not on that queue, but attempting to do anything with that instance without first dispatching to the queue will throw an incorrect thread exception.
The default Realm is created using the default
RLMRealmConfiguration
, which can be changed via+[RLMRealmConfiguration setDefaultConfiguration:]
.Declaration
Objective-C
+ (nonnull instancetype)defaultRealmForQueue:(nonnull dispatch_queue_t)queue;
Swift
class func defaultRealm(for queue: dispatch_queue_t) -> Self
Parameters
queue
A serial dispatch queue to confine the Realm to.
Return Value
The default
RLMRealm
instance for the given queue. -
Obtains an
RLMRealm
instance with the given configuration.Declaration
Objective-C
+ (nullable instancetype) realmWithConfiguration:(nonnull RLMRealmConfiguration *)configuration error:(NSError *_Nullable *_Nullable)error;
Swift
convenience init(configuration: RLMRealmConfiguration) throws
Parameters
configuration
A configuration object to use when creating the Realm.
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
An
RLMRealm
instance. -
Obtains an
RLMRealm
instance with the given configuration bound to the given queue.Rather than being confined to the thread they are opened on, queue-bound RLMRealms are confined to the given queue. They can be accessed from any thread as long as it is from within a block dispatch to the queue, and notifications will be delivered to the queue instead of a thread’s run loop.
Realms can only be confined to a serial queue. Queue-confined RLMRealm instances can be obtained when not on that queue, but attempting to do anything with that instance without first dispatching to the queue will throw an incorrect thread exception.
Declaration
Objective-C
+ (nullable instancetype) realmWithConfiguration:(nonnull RLMRealmConfiguration *)configuration queue:(nullable dispatch_queue_t)queue error:(NSError *_Nullable *_Nullable)error;
Swift
convenience init(configuration: RLMRealmConfiguration, queue: dispatch_queue_t?) throws
Parameters
configuration
A configuration object to use when creating the Realm.
queue
A serial dispatch queue to confine the Realm to.
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
An
RLMRealm
instance. -
Obtains an
RLMRealm
instance persisted at a specified file URL.Declaration
Objective-C
+ (nonnull instancetype)realmWithURL:(nonnull NSURL *)fileURL;
Swift
convenience init(url fileURL: URL)
Parameters
fileURL
The local URL of the file the Realm should be saved at.
Return Value
An
RLMRealm
instance. -
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
-[RLMRealm realmWithConfiguration:queue:error]
was used.Declaration
Objective-C
+ (nonnull RLMAsyncOpenTask *) asyncOpenWithConfiguration:(nonnull RLMRealmConfiguration *)configuration callbackQueue:(nonnull dispatch_queue_t)callbackQueue callback:(nonnull RLMAsyncOpenRealmCallback)callback;
Swift
class func asyncOpen(with configuration: RLMRealmConfiguration, callbackQueue: dispatch_queue_t, callback: @escaping RLMAsyncOpenRealmCallback) -> RLMAsyncOpenTask
Parameters
configuration
A configuration object to use when opening the Realm.
callbackQueue
The serial dispatch queue on which the callback should be run.
callback
A callback block. If the Realm was successfully opened, it will be passed in as an argument. Otherwise, an
NSError
describing what went wrong will be passed to the block instead. -
Indicates if the Realm is currently engaged 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
Objective-C
@property (nonatomic, readonly) BOOL inWriteTransaction;
Swift
var inWriteTransaction: Bool { get }
-
The
RLMRealmConfiguration
object that was used to create thisRLMRealm
instance.Declaration
Objective-C
@property (nonatomic, readonly) RLMRealmConfiguration *_Nonnull configuration;
Swift
var configuration: RLMRealmConfiguration { get }
-
Indicates if this Realm contains any objects.
Declaration
Objective-C
@property (nonatomic, readonly) BOOL isEmpty;
Swift
var isEmpty: Bool { get }
-
Indicates if this Realm is frozen.
Declaration
Objective-C
@property (nonatomic, readonly, getter=isFrozen) BOOL frozen;
Swift
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 RLMRealm 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.
Declaration
Objective-C
- (nonnull RLMRealm *)freeze;
Swift
func freeze() -> RLMRealm
-
Returns a live reference of this Realm.
All objects and collections read from the returned Realm will no longer be frozen. This method will return
self
if it is not already frozen.Declaration
Objective-C
- (nonnull RLMRealm *)thaw;
Swift
func thaw() -> RLMRealm
-
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.
Declaration
Objective-C
- (BOOL)writeCopyToURL:(nonnull NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError *_Nullable *_Nullable)error;
Swift
func writeCopy(to fileURL: URL, encryptionKey key: Data?) throws
Parameters
fileURL
Local URL to save the Realm to.
key
Optional 64-byte encryption key to encrypt the new file with.
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
YES
if the Realm was successfully written to disk,NO
if an error occurred. -
Writes a copy of the Realm to a given location specified by a given configuration.
If the configuration supplied is derived from a
RLMUser
then this Realm will be copied with sync functionality enabled.The destination file cannot already exist.
Declaration
Objective-C
- (BOOL)writeCopyForConfiguration:(nonnull RLMRealmConfiguration *)configuration error:(NSError *_Nullable *_Nullable)error;
Swift
func writeCopy(for configuration: RLMRealmConfiguration) throws
Parameters
configuration
A Realm Configuration.
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
YES
if the Realm was successfully written to disk,NO
if an error occurred. -
Checks if the Realm file for the given configuration exists locally on disk.
For non-synchronized, non-in-memory Realms, this is equivalent to
-[NSFileManager.defaultManager fileExistsAtPath:config.path]
. 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.Declaration
Objective-C
+ (BOOL)fileExistsForConfiguration:(nonnull RLMRealmConfiguration *)config;
Swift
class func fileExists(for config: RLMRealmConfiguration) -> Bool
Parameters
config
A Realm configuration to check the existence of.
Return Value
YES if the Realm file for the given configuration exists on disk, NO otherwise.
-
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 return NO and report the error RLMErrorAlreadyOpen. 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
NO
and report the error NSFileNoSuchFileError;Declaration
Objective-C
+ (BOOL)deleteFilesForConfiguration:(nonnull RLMRealmConfiguration *)config error:(NSError *_Nullable *_Nullable)error;
Swift
class func deleteFiles(for config: RLMRealmConfiguration) throws -> Bool
Parameters
config
A Realm configuration identifying the Realm to be deleted.
Return Value
YES if any files were deleted, NO otherwise.
-
Adds a notification handler for changes in this Realm, and returns a notification token.
Notification handlers are called after each write transaction is committed, either on the current thread or other threads.
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.
The block has the following definition:
typedef void(^RLMNotificationBlock)(RLMNotification notification, RLMRealm *realm);
It receives the following parameters:
NSString
*notification: The name of the incoming notification. SeeRLMRealmNotification
for information on what notifications are sent.RLMRealm
*realm: The Realm for which this notification occurred.
Declaration
Objective-C
- (nonnull RLMNotificationToken *)addNotificationBlock: (nonnull RLMNotificationBlock)block;
Swift
func addNotificationBlock(_ block: @escaping RLMNotificationBlock) -> RLMNotificationToken
Parameters
block
A block which is called to process Realm notifications.
Return Value
A token object which must be retained as long as you wish to continue receiving change notifications.
-
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
beginWriteTransaction
fromRLMRealm
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,
beginWriteTransaction
updates theRLMRealm
instance 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
Objective-C
- (void)beginWriteTransaction;
Swift
func beginWriteTransaction()
-
Commits all write operations in the current write transaction, and ends the transaction.
After saving the changes, all notification blocks registered on this specific
RLMRealm
instance are invoked synchronously. Notification blocks registered on other threads or on collections are invoked asynchronously. If you do not want to receive a specific notification for this write tranaction, seecommitWriteTransactionWithoutNotifying:error:
.This method can fail if there is insufficient disk space available to save the writes made, or due to unexpected i/o errors. This version of the method throws an exception when errors occur. Use the version with a
NSError
out parameter instead if you wish to handle errors.Warning
This method may only be called during a write transaction.Declaration
Objective-C
- (void)commitWriteTransaction;
-
Commits all write operations in the current write transaction, and ends the transaction.
After saving the changes, all notification blocks registered on this specific
RLMRealm
instance are invoked synchronously. Notification blocks registered on other threads or on collections are invoked asynchronously. If you do not want to receive a specific notification for this write tranaction, seecommitWriteTransactionWithoutNotifying:error:
.This method can fail if there is insufficient disk space available to save the writes made, or due to unexpected i/o errors.
Warning
This method may only be called during a write transaction.
Declaration
Objective-C
- (BOOL)commitWriteTransaction:(NSError *_Nullable *_Nullable)error;
Swift
func commitWriteTransaction() throws
Parameters
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
Whether the transaction succeeded.
-
Commits all write operations in the current write transaction, without notifying specific notification blocks of the changes.
After saving the changes, all notification blocks registered on this specific
RLMRealm
instance are invoked synchronously. Notification blocks registered on other threads or on collections are scheduled to be invoked asynchronously.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 method must be for notifications for this specific
RLMRealm
instance. Notifications for different threads cannot be skipped using this method.This method can fail if there is insufficient disk space available to save the writes made, or due to unexpected i/o errors.
Warning
This method may only be called during a write transaction.
Declaration
Objective-C
- (BOOL)commitWriteTransactionWithoutNotifying: (nonnull NSArray<RLMNotificationToken *> *)tokens error:(NSError *_Nullable *_Nullable) error;
Swift
func commitWriteTransactionWithoutNotifying(_ tokens: [RLMNotificationToken]) 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.
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
Whether the transaction succeeded.
-
Reverts all writes made during 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
RLMObject
s which were added to the Realm will be invalidated rather than becoming unmanaged. Given the following code:ObjectType *oldObject = [[ObjectType objectsWhere:@"..."] firstObject]; ObjectType *newObject = [[ObjectType alloc] init]; [realm beginWriteTransaction]; [realm addObject:newObject]; [realm deleteObject:oldObject]; [realm cancelWriteTransaction];
Both
oldObject
andnewObject
will returnYES
forisInvalidated
, but re-running the query which providedoldObject
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 notifications are produced by a cancelled write transaction.
Warning
This method may only be called during a write transaction.Declaration
Objective-C
- (void)cancelWriteTransaction;
Swift
func cancelWriteTransaction()
-
Performs actions contained within the given block inside a write transaction.
See
[RLMRealm transactionWithoutNotifying:block:error:]
Declaration
Objective-C
- (void)transactionWithBlock:(nonnull void (^)(void))block;
-
Performs actions contained within the given block inside a write transaction.
See
[RLMRealm transactionWithoutNotifying:block:error:]
Declaration
Objective-C
- (BOOL)transactionWithBlock:(nonnull void (^)(void))block error:(NSError *_Nullable *_Nullable)error;
Swift
func transaction(_ block: () -> Void) throws
-
Performs actions contained within the given block inside a write transaction.
See
[RLMRealm transactionWithoutNotifying:block:error:]
Declaration
Objective-C
- (void)transactionWithoutNotifying: (nonnull NSArray<RLMNotificationToken *> *)tokens block:(nonnull void (^)(void))block;
Swift
func transactionWithoutNotifying(_ tokens: [RLMNotificationToken], block: () -> Void)
-
Performs actions contained within the given block inside a write transaction.
Write transactions cannot be nested, and trying to execute a write transaction on a Realm which is already participating in a write transaction will throw an exception. Calls to
transactionWithBlock:
fromRLMRealm
instances in other threads will block until the current write transaction completes.Before beginning the write transaction,
transactionWithBlock:
updates theRLMRealm
instance 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 method must be for notifications for this specific
RLMRealm
instance. Notifications for different threads cannot be skipped using this method.Declaration
Objective-C
- (BOOL)transactionWithoutNotifying: (nonnull NSArray<RLMNotificationToken *> *)tokens block:(nonnull void (^)(void))block error:(NSError *_Nullable *_Nullable)error;
Swift
func transactionWithoutNotifying(_ tokens: [RLMNotificationToken], block: () -> Void, error: ()) 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.
block
The block containing actions to perform.
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
Whether the transaction succeeded.
-
Indicates if the Realm is currently performing async write operations. This becomes YES following a call to
beginAsyncWriteTransaction
,commitAsyncWriteTransaction
, orasyncTransactionWithBlock:
, and remains so until all scheduled async write work has completed.Warning
If this isYES
, closing or invalidating the Realm will block until scheduled work has completed.Declaration
Objective-C
@property (nonatomic, readonly) BOOL isPerformingAsynchronousWriteOperations;
Swift
var isPerformingAsynchronousWriteOperations: Bool { get }
-
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
beginWriteTransaction
, 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.Declaration
Objective-C
- (RLMAsyncTransactionId)beginAsyncWriteTransaction: (nonnull void (^)(void))block;
Swift
func beginAsyncWriteTransaction(_ block: @escaping () -> Void) -> RLMAsyncTransactionId
Parameters
block
The block containing actions to perform inside the write transaction.
block
should end by callingcommitAsyncWriteTransaction
,commitWriteTransaction
orcancelWriteTransaction
. Returning without one of these calls is equivalent to callingcancelWriteTransaction
.Return Value
An id identifying the asynchronous transaction which can be passed to
cancelAsyncTransaction:
prior to the block being called to cancel the pending invocation of the block. -
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
beginWriteTransaction
orbeginAsyncWriteTransaction
.Declaration
Objective-C
- (RLMAsyncTransactionId)commitAsyncWriteTransaction: (nullable void (^)(NSError *_Nullable)) completionBlock allowGrouping:(BOOL)allowGrouping;
Swift
@_unsafeInheritExecutor func commitAsyncWriteTransaction(_ completionBlock: (((any Error)?) -> Void)?, allowGrouping: Bool) -> RLMAsyncTransactionId
Parameters
completionBlock
A block which will be called on the source thread or queue once the commit has either completed or failed with an error.
allowGrouping
If
YES
, multiple sequential calls tocommitAsyncWriteTransaction:
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 Value
An id identifying the asynchronous transaction commit can be passed to
cancelAsyncTransaction:
prior to the completion block being called to cancel the pending invocation of the block. Note that this does not cancel the commit itself. -
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
beginWriteTransaction
orbeginAsyncWriteTransaction
.Declaration
Objective-C
- (RLMAsyncTransactionId)commitAsyncWriteTransaction: (nonnull void (^)(NSError *_Nullable))completionBlock;
Swift
func commitAsyncWriteTransaction(_ completionBlock: @escaping ((any Error)?) -> Void) -> RLMAsyncTransactionId
Parameters
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 Value
An id identifying the asynchronous transaction commit can be passed to
cancelAsyncTransaction:
prior to the completion block being called to cancel the pending invocation of the block. Note that this does not cancel the commit itself. -
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
beginWriteTransaction
orbeginAsyncWriteTransaction
.Declaration
Objective-C
- (RLMAsyncTransactionId)commitAsyncWriteTransaction;
Swift
func commitAsyncWriteTransaction() -> RLMAsyncTransactionId
Return Value
An id identifying the asynchronous transaction commit can be passed to
cancelAsyncTransaction:
prior to the completion block being called to cancel the pending invocation of the block. Note that this does not cancel the commit itself. -
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
cancelAsyncTransaction:
from within the block is a no-op.Declaration
Objective-C
- (void)cancelAsyncTransaction:(RLMAsyncTransactionId)asyncTransactionId;
Swift
func cancelAsyncTransaction(_ asyncTransactionId: RLMAsyncTransactionId)
Parameters
asyncTransactionId
A transaction id from either
beginAsyncWriteTransaction:
orcommitAsyncWriteTransaction:
. -
Asynchronously performs actions contained within the given block inside a write transaction. The write transaction is begun asynchronously as if calling
beginAsyncWriteTransaction:
, and by default the transaction is commited asynchronously after the block completes. You can also explicitly callcommitWriteTransaction
orcancelWriteTransaction
from within the block to synchronously commit or cancel the write transaction.Declaration
Objective-C
- (RLMAsyncTransactionId) asyncTransactionWithBlock:(nonnull void (^)(void))block onComplete: (nullable void (^)(NSError *_Nonnull))completionBlock;
Swift
func asyncTransaction(_ block: @escaping () -> Void, onComplete completionBlock: ((any Error) -> Void)? = nil) -> RLMAsyncTransactionId
Parameters
block
The block containing actions to perform.
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 Value
An id identifying the asynchronous transaction which can be passed to
cancelAsyncTransaction:
prior to the block being called to cancel the pending invocation of the block. -
Asynchronously performs actions contained within the given block inside a write transaction. The write transaction is begun asynchronously as if calling
beginAsyncWriteTransaction:
, and by default the transaction is commited asynchronously after the block completes. You can also explicitly callcommitWriteTransaction
orcancelWriteTransaction
from within the block to synchronously commit or cancel the write transaction.Declaration
Objective-C
- (RLMAsyncTransactionId)asyncTransactionWithBlock: (nonnull void (^)(void))block;
Swift
func asyncTransaction(_ block: @escaping () -> Void) -> RLMAsyncTransactionId
Parameters
block
The block containing actions to perform.
Return Value
An id identifying the asynchronous transaction which can be passed to
cancelAsyncTransaction:
prior to the block being called to cancel the pending invocation of the block. -
Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
If the version of the Realm is actually changed, Realm and collection notifications will be sent to reflect the changes. This may take some time, as collection notifications are prepared on a background thread. As a result, calling this method on the main thread is not advisable.
Declaration
Objective-C
- (BOOL)refresh;
Swift
func refresh() -> Bool
Return Value
Whether there were any updates for the Realm. Note that
YES
may be returned even if no data actually changed. -
Set this property to
YES
to automatically update this Realm when changes happen in other threads.If set to
YES
(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 toNO
, 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 ifautorefresh
is set toYES
.Even with this property enabled, you can still call
-refresh
at any time to update the Realm before the automatic refresh would occur.Write transactions will still always advance a Realm to the latest version and produce local notifications on commit even if autorefresh is disabled.
Disabling
autorefresh
on a Realm without any strong references to it will not have any effect, andautorefresh
will revert back toYES
the next time the Realm is created. This is normally irrelevant as it means that there is nothing to refresh (as managedRLMObject
s,RLMArray
s, andRLMResults
have strong references to the Realm that manages them), but it means that settingRLMRealm.defaultRealm.autorefresh = NO
inapplication:didFinishLaunchingWithOptions:
and only later storing Realm objects will not work.Defaults to
YES
.Declaration
Objective-C
@property (nonatomic) BOOL autorefresh;
Swift
var autorefresh: Bool { get set }
-
Invalidates all
RLMObject
s,RLMResults
,RLMLinkingObjects
, andRLMArray
s 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
RLMObject
,RLMResults
andRLMArray
instances obtained from thisRLMRealm
instance on the current thread are invalidated.RLMObject
s andRLMArray
s cannot be used.RLMResults
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
Objective-C
- (void)invalidate;
Swift
func invalidate()
-
Returns the same object as the one referenced when the
RLMThreadSafeReference
was first created, but resolved for the current Realm for this thread. Returnsnil
if this object was deleted after the reference was created.Warning
A
RLMThreadSafeReference
object must be resolved at most once. Failing to resolve aRLMThreadSafeReference
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.
Declaration
Objective-C
- (nullable id)resolveThreadSafeReference: (nonnull RLMThreadSafeReference *)reference;
Parameters
reference
The thread-safe reference to the thread-confined object to resolve in this Realm.
-
Adds an object to the Realm.
Once added, this object is considered to be managed by the Realm. It can be retrieved using the
objectsWhere:
selectors onRLMRealm
and on subclasses ofRLMObject
.When added, all child relationships referenced by this object will also be added to the Realm if they are not already in it.
If the object or any related objects are already being managed by a different Realm an exception will be thrown. Use
-[RLMObject createInRealm:withObject:]
to insert a copy of a managed object into a different Realm.The object to be added must be valid and cannot have been previously deleted from a Realm (i.e.
isInvalidated
must beNO
).Warning
This method may only be called during a write transaction.
Declaration
Objective-C
- (void)addObject:(nonnull RLMObject *)object;
Swift
func add(_ object: RLMObject)
Parameters
object
The object to be added to this Realm.
-
Adds all the objects in a collection to the Realm.
This is the equivalent of calling
addObject:
for every object in a collection.Warning
This method may only be called during a write transaction.
See
addObject:
Declaration
Objective-C
- (void)addObjects:(nonnull id<NSFastEnumeration>)objects;
Swift
func addObjects(_ objects: any NSFastEnumeration)
Parameters
objects
An enumerable collection such as
NSArray
,RLMArray
, orRLMResults
, containing Realm objects to be added to the Realm. -
Adds or updates an existing object into the Realm.
The object provided must have a designated primary key. If no objects exist in the Realm with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.
As with
addObject:
, the object cannot already be managed by a different Realm. Use-[RLMObject createOrUpdateInRealm:withValue:]
to copy values to a different Realm.If there is a property or KVC value on
object
whose value is nil, and it corresponds to a nullable property on an existing object being updated, that nullable property will be set to nil.Warning
This method may only be called during a write transaction.
Declaration
Objective-C
- (void)addOrUpdateObject:(nonnull RLMObject *)object;
Swift
func addOrUpdate(_ object: RLMObject)
Parameters
object
The object to be added or updated.
-
Adds or updates all the objects in a collection into the Realm.
This is the equivalent of calling
addOrUpdateObject:
for every object in a collection.Warning
This method may only be called during a write transaction.
See
addOrUpdateObject:
Declaration
Objective-C
- (void)addOrUpdateObjects:(nonnull id<NSFastEnumeration>)objects;
Swift
func addOrUpdateObjects(_ objects: any NSFastEnumeration)
Parameters
objects
An enumerable collection such as
NSArray
,RLMArray
, orRLMResults
, containing Realm objects to be added to or updated within the Realm. -
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
Objective-C
- (void)deleteObject:(nonnull RLMObject *)object;
Swift
func delete(_ object: RLMObject)
Parameters
object
The object to be deleted.
-
Deletes one or more objects from the Realm.
This is the equivalent of calling
deleteObject:
for every object in a collection.Warning
This method may only be called during a write transaction.
See
deleteObject:
Declaration
Objective-C
- (void)deleteObjects:(nonnull id<NSFastEnumeration>)objects;
Swift
func deleteObjects(_ objects: any NSFastEnumeration)
Parameters
objects
An enumerable collection such as
NSArray
,RLMArray
, orRLMResults
, containing objects to be deleted from the Realm. -
Deletes all objects from the Realm.
Warning
This method may only be called during a write transaction.
See
deleteObject:
Declaration
Objective-C
- (void)deleteAllObjects;
Swift
func deleteAllObjects()
-
Represents 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.
Declaration
Objective-C
@property (nonatomic, readonly, nonnull) RLMSyncSubscriptionSet *subscriptions;
Swift
var subscriptions: RLMSyncSubscriptionSet { get }
-
Returns the schema version for a Realm at a given local URL.
Declaration
Objective-C
+ (uint64_t)schemaVersionAtURL:(nonnull NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError *_Nullable *_Nullable)error;
Parameters
fileURL
Local URL to a Realm file.
key
64-byte key used to encrypt the file, or
nil
if it is unencrypted.error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.Return Value
The version of the Realm at
fileURL
, orRLMNotVersioned
if the version cannot be read. -
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.
See
RLMMigration
Declaration
Objective-C
+ (BOOL)performMigrationForConfiguration: (nonnull RLMRealmConfiguration *)configuration error:(NSError *_Nullable *_Nullable)error;
Swift
class func performMigration(for configuration: RLMRealmConfiguration) throws
Parameters
configuration
The Realm configuration used to open and migrate the Realm.
Return Value
The error that occurred while applying the migration, if any.
-
Unavailable
Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:.
RLMRealm instances are cached internally by Realm and cannot be created directly.
Use
+[RLMRealm defaultRealm]
,+[RLMRealm realmWithConfiguration:error:]
or+[RLMRealm realmWithURL]
to obtain a reference to an RLMRealm.Declaration
Objective-C
- (nonnull instancetype)init;
-
Unavailable
Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:.
RLMRealm instances are cached internally by Realm and cannot be created directly.
Use
+[RLMRealm defaultRealm]
,+[RLMRealm realmWithConfiguration:error:]
or+[RLMRealm realmWithURL]
to obtain a reference to an RLMRealm.Declaration
Objective-C
+ (nonnull instancetype)new;
-
Get the RLMSyncSession used by this Realm. Will be nil if this is not a synchronized Realm.
Declaration
Objective-C
@property (nonatomic, readonly, nullable) RLMSyncSession *syncSession;
Swift
var syncSession: RLMSyncSession? { get }