RLMRealm
@interface 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 (with 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 a RLMRealm object 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
RLMRealm instances are not thread safe and can not be shared across threads or dispatch queues. 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 on a consistent thread.-
Obtains an instance of the default Realm.
The default Realm is used by the
RLMObjectclass methods which do not take aRLMRealmparameter, but is otherwise not special. 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
RLMRealmConfiguration, which can be changed via+[RLMRealmConfiguration setDefaultConfiguration:].Declaration
Objective‑C
+ (nonnull instancetype)defaultRealm;Swift
class func defaultRealm() -> SelfReturn Value
The default
RLMRealminstance for the current thread. -
Obtains an
RLMRealminstance with the given configuration.Declaration
Objective‑C
+ (nullable instancetype) realmWithConfiguration:(nonnull RLMRealmConfiguration *)configuration error:(NSError *_Nullable *_Nullable)error;Swift
convenience init(configuration: RLMRealmConfiguration) throwsParameters
configurationThe configuration for the realm.
errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
An
RLMRealminstance. -
The RLMSchema used by this RLMRealm.
Declaration
Objective‑C
@property (readonly, nonatomic, null_unspecified) RLMSchema *schema;Swift
var schema: RLMSchema! { get } -
Indicates if this Realm is currently in a write transaction.
Warning
Wrapping mutating operations in a write transaction if this property returnsNOmay cause a large number of write transactions to be created, which could negatively impact Realm’s performance. Always prefer performing multiple mutations in a single transaction when possible.Declaration
Objective‑C
@property (readonly, nonatomic) BOOL inWriteTransaction;Swift
var inWriteTransaction: Bool { get } -
Returns the
RLMRealmConfigurationthat was used to create thisRLMRealminstance.Declaration
Objective‑C
@property (readonly, nonatomic) RLMRealmConfiguration *_Nonnull configuration;Swift
var configuration: RLMRealmConfiguration { get } -
Indicates if this Realm contains any objects.
Declaration
Objective‑C
@property (readonly, nonatomic) BOOL isEmpty;Swift
var isEmpty: Bool { get }
-
Add a notification handler for changes in this RLMRealm.
Notification handlers are called after each write transaction is committed, either on the current thread or other threads. The block is called on the same thread as they were added on, and can 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 normally will only be the main thread.
The block has the following definition:
typedef void(^RLMNotificationBlock)(NSString *notification, RLMRealm *realm);It receives the following parameters:
NSString*notification: The name of the incoming notification. See RLMRealmNotification 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
@warn_unused_result func addNotificationBlock(block: RLMNotificationBlock) -> RLMNotificationTokenParameters
blockA block which is called to process RLMRealm notifications.
Return Value
A token object which must be stored as long as you wish to continue receiving change notifications.
-
Begins a write transaction in an
RLMRealm.Only one write transaction can be open at a time. Write transactions cannot be nested, and trying to begin a write transaction on a
RLMRealmwhich is already in a write transaction will throw an exception. Calls tobeginWriteTransactionfromRLMRealminstances in other threads will block until the current write transaction completes.Before beginning the write transaction,
beginWriteTransactionupdates theRLMRealmto the latest Realm version, as if refresh was called, and generates notifications if applicable. This has no effect if theRLMRealmwas 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
RLMRealmin 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.
Warning
This method can 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.
Warning
This method can only be called during a write transaction.
Declaration
Objective‑C
- (BOOL)commitWriteTransaction:(NSError *_Nullable *_Nullable)error;Swift
func commitWriteTransaction() throwsParameters
errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
Whether the transaction succeeded.
-
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
RLMObjects which were added to the Realm will be invalidated rather than switching back to standalone objects. 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
oldObjectandnewObjectwill returnYESforisInvalidated, but re-running the query which providedoldObjectwill once again return the valid object.Warning
This method can only be called during a write transaction.Declaration
Objective‑C
- (void)cancelWriteTransaction;Swift
func cancelWriteTransaction() -
Helper to perform a block within a transaction.
Declaration
Objective‑C
- (void)transactionWithBlock:(nonnull void (^)(void))block; -
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
RLMRealmwhich is already in a write transaction will throw an exception. Calls totransactionWithBlock:fromRLMRealminstances in other threads will block until the current write transaction completes.Before beginning the write transaction,
transactionWithBlock:updates theRLMRealmto the latest Realm version, as if refresh was called, and generates notifications if applicable. This has no effect if theRLMRealmwas already up to date.Declaration
Objective‑C
- (BOOL)transactionWithBlock:(nonnull void (^)(void))block error:(NSError *_Nullable *_Nullable)error;Swift
func transactionWithBlock(@noescape block: () -> Void) throwsParameters
blockThe block to perform.
errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
Whether the transaction succeeded.
-
Declaration
Objective‑C
- (BOOL)refresh;Swift
func refresh() -> BoolReturn Value
Whether the realm had any updates. Note that this may return YES even if no data has actually changed.
-
Set 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 to NO, you must manually call
-refreshon the Realm to update it to get the latest version.Note that by default, background threads do not have an active run loop and you will need to manually call
-refreshin order to update to the latest version, even ifautorefreshis set totrue.Even with this enabled, you can still call
-refreshat any time to update the Realm before the automatic refresh would occur.Notifications are sent when a write transaction is committed whether or not this is enabled.
Disabling this on an
RLMRealmwithout any strong references to it will not have any effect, and it will switch back to YES the next time theRLMRealmobject is created. This is normally irrelevant as it means that there is nothing to refresh (as persistedRLMObjects,RLMArrays, andRLMResultshave strong references to the containingRLMRealm), but it means that settingRLMRealm.defaultRealm.autorefresh = NOinapplication:didFinishLaunchingWithOptions:and only later storing Realm objects will not work.Defaults to YES.
Declaration
Objective‑C
@property (assign, readwrite, nonatomic) BOOL autorefresh;Swift
var autorefresh: Bool { get set } -
Write a compacted and optionally encrypted copy of the RLMRealm to the given local URL.
The destination file cannot already exist.
Note that if this is called from within a write transaction it writes the current data, and not data when the last write transaction was committed.
Declaration
Objective‑C
- (BOOL)writeCopyToURL:(nonnull NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError *_Nullable *_Nullable)error;Swift
func writeCopyToURL(fileURL: NSURL, encryptionKey key: NSData?) throwsParameters
fileURLLocal URL to save the Realm to.
keyOptional 64-byte encryption key to encrypt the new file with.
errorOn input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information.
Return Value
YES if the realm was copied successfully. Returns NO if an error occurred.
-
Invalidate all RLMObjects and RLMResults read from this Realm.
An RLMRealm 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 RLMRealm. 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,RLMResultsandRLMArrayinstances obtained from thisRLMRealmon the current thread are invalidated, and can not longer be used. TheRLMRealmitself 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 cannot be called on a read-only Realm.
Declaration
Objective‑C
- (void)invalidate;Swift
func invalidate()
-
Adds an object to be persisted in this Realm.
Once added, this object can be retrieved using the
objectsWhere:selectors onRLMRealmand 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 already belong to a different Realm an exception will be thrown. Use-[RLMObject createInRealm:withObject]to insert a copy of a persisted 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 be false.Warning
This method can only be called during a write transaction.
Declaration
Objective‑C
- (void)addObject:(nonnull RLMObject *)object;Swift
func addObject(object: RLMObject)Parameters
objectObject to be added to this Realm.
-
Adds objects in the given array to be persisted in this Realm.
This is the equivalent of
addObject:except for an array of objects.Warning
This method can only be called during a write transaction.
See
addObject:
Declaration
Objective‑C
- (void)addObjects:(nonnull id<NSFastEnumeration>)array;Swift
func addObjects(array: NSFastEnumeration)Parameters
arrayAn enumerable object such as NSArray or RLMResults which contains objects to be added to this Realm.
-
Adds or updates an object to be persisted in this Realm. The object provided must have a designated primary key. If no objects exist in the RLMRealm instance 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 persisted in a different Realm. Use-[RLMObject createOrUpdateInRealm:withValue:]to copy values to a different Realm.Warning
This method can only be called during a write transaction.
Declaration
Objective‑C
- (void)addOrUpdateObject:(nonnull RLMObject *)object;Swift
func addOrUpdateObject(object: RLMObject)Parameters
objectObject to be added or updated.
-
Adds or updates objects in the given array to be persisted in this Realm.
This is the equivalent of
addOrUpdateObject:except for an array of objects.Warning
This method can only be called during a write transaction.
See
addOrUpdateObject:
Declaration
Objective‑C
- (void)addOrUpdateObjectsFromArray:(nonnull id)array;Swift
func addOrUpdateObjectsFromArray(array: AnyObject)Parameters
arrayNSArray,RLMArray, orRLMResultsofRLMObjects (or subclasses) to be added to this Realm. -
Delete an object from this Realm.
Warning
This method can only be called during a write transaction.
Declaration
Objective‑C
- (void)deleteObject:(nonnull RLMObject *)object;Swift
func deleteObject(object: RLMObject)Parameters
objectObject to be deleted from this Realm.
-
Delete an
NSArray,RLMArray, orRLMResultsof objects from this Realm.Warning
This method can only be called during a write transaction.
Declaration
Objective‑C
- (void)deleteObjects:(nonnull id)array;Swift
func deleteObjects(array: AnyObject)Parameters
arrayRLMArray,NSArray, orRLMResultsofRLMObjects to be deleted. -
Deletes all objects in this Realm.
Warning
This method can only be called during a write transaction.Declaration
Objective‑C
- (void)deleteAllObjects;Swift
func deleteAllObjects()
-
Get 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;Swift
class func schemaVersionAtURL(fileURL: NSURL, encryptionKey key: NSData?, error: NSErrorPointer) -> UInt64Parameters
fileURLLocal URL to a Realm file.
key64-byte key used to encrypt the file, or nil if it is unencrypted.
errorIf an error occurs, upon return contains an
NSErrorobject that describes the problem. If you are not interested in possible errors, pass inNULL.Return Value
The version of the Realm at
fileURLor RLMNotVersioned 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
+ (nonnull NSError *)migrateRealm: (nonnull RLMRealmConfiguration *)configuration;Swift
class func migrateRealm(configuration: RLMRealmConfiguration) -> NSErrorParameters
configurationThe Realm configuration used to open and migrate the Realm.
Return Value
The error that occurred while applying the migration, if any.
View on GitHub
Install in Dash
RLMRealm Class Reference