1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2014 Realm Inc.
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
17 ////////////////////////////////////////////////////////////////////////////
19 #import <Foundation/Foundation.h>
20 #import "RLMConstants.h"
22 @class RLMRealmConfiguration, RLMRealm, RLMObject, RLMSchema, RLMMigration, RLMNotificationToken, RLMThreadSafeReference;
25 A callback block for opening Realms asynchronously.
27 Returns the Realm if the open was successful, or an error otherwise.
29 typedef void(^RLMAsyncOpenRealmCallback)(RLMRealm * _Nullable realm, NSError * _Nullable error);
31 NS_ASSUME_NONNULL_BEGIN
34 An `RLMRealm` instance (also referred to as "a Realm") represents a Realm
37 Realms can either be stored on disk (see `+[RLMRealm realmWithURL:]`) or in
38 memory (see `RLMRealmConfiguration`).
40 `RLMRealm` instances are cached internally, and constructing equivalent `RLMRealm`
41 objects (for example, by using the same path or identifier) multiple times on a single thread
42 within a single iteration of the run loop will normally return the same
45 If you specifically want to ensure an `RLMRealm` instance is
46 destroyed (for example, if you wish to open a Realm, check some property, and
47 then possibly delete the Realm file and re-open it), place the code which uses
48 the Realm within an `@autoreleasepool {}` and ensure you have no other
49 strong references to it.
51 @warning `RLMRealm` instances are not thread safe and cannot be shared across
52 threads or dispatch queues. Trying to do so will cause an exception to be thrown.
53 You must call this method on each thread you want
54 to interact with the Realm on. For dispatch queues, this means that you must
55 call it in each block which is dispatched, as a queue is not guaranteed to run
56 all of its blocks on the same thread.
59 @interface RLMRealm : NSObject
61 #pragma mark - Creating & Initializing a Realm
64 Obtains an instance of the default Realm.
66 The default Realm is used by the `RLMObject` class methods
67 which do not take an `RLMRealm` parameter, but is otherwise not special. The
68 default Realm is persisted as *default.realm* under the *Documents* directory of
69 your Application on iOS, and in your application's *Application Support*
72 The default Realm is created using the default `RLMRealmConfiguration`, which
73 can be changed via `+[RLMRealmConfiguration setDefaultConfiguration:]`.
75 @return The default `RLMRealm` instance for the current thread.
77 + (instancetype)defaultRealm;
80 Obtains an `RLMRealm` instance with the given configuration.
82 @param configuration A configuration object to use when creating the Realm.
83 @param error If an error occurs, upon return contains an `NSError` object
84 that describes the problem. If you are not interested in
85 possible errors, pass in `NULL`.
87 @return An `RLMRealm` instance.
89 + (nullable instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error;
92 Obtains an `RLMRealm` instance persisted at a specified file URL.
94 @param fileURL The local URL of the file the Realm should be saved at.
96 @return An `RLMRealm` instance.
98 + (instancetype)realmWithURL:(NSURL *)fileURL;
101 Asynchronously open a Realm and deliver it to a block on the given queue.
103 Opening a Realm asynchronously will perform all work needed to get the Realm to
104 a usable state (such as running potentially time-consuming migrations) on a
105 background thread before dispatching to the given queue. In addition,
106 synchronized Realms wait for all remote content available at the time the
107 operation began to be downloaded and available locally.
109 @param configuration A configuration object to use when opening the Realm.
110 @param callbackQueue The dispatch queue on which the callback should be run.
111 @param callback A callback block. If the Realm was successfully opened,
112 it will be passed in as an argument.
113 Otherwise, an `NSError` describing what went wrong will be
114 passed to the block instead.
116 @note The returned Realm is confined to the thread on which it was created.
117 Because GCD does not guarantee that queues will always use the same
118 thread, accessing the returned Realm outside the callback block (even if
119 accessed from `callbackQueue`) is unsafe.
121 + (void)asyncOpenWithConfiguration:(RLMRealmConfiguration *)configuration
122 callbackQueue:(dispatch_queue_t)callbackQueue
123 callback:(RLMAsyncOpenRealmCallback)callback;
126 The `RLMSchema` used by the Realm.
128 @property (nonatomic, readonly) RLMSchema *schema;
131 Indicates if the Realm is currently engaged in a write transaction.
133 @warning Do not simply check this property and then start a write transaction whenever an object needs to be
134 created, updated, or removed. Doing so might cause a large number of write transactions to be created,
135 degrading performance. Instead, always prefer performing multiple updates during a single transaction.
137 @property (nonatomic, readonly) BOOL inWriteTransaction;
140 The `RLMRealmConfiguration` object that was used to create this `RLMRealm` instance.
142 @property (nonatomic, readonly) RLMRealmConfiguration *configuration;
145 Indicates if this Realm contains any objects.
147 @property (nonatomic, readonly) BOOL isEmpty;
149 #pragma mark - Notifications
152 The type of a block to run whenever the data within the Realm is modified.
154 @see `-[RLMRealm addNotificationBlock:]`
156 typedef void (^RLMNotificationBlock)(RLMNotification notification, RLMRealm *realm);
158 #pragma mark - Receiving Notification when a Realm Changes
161 Adds a notification handler for changes in this Realm, and returns a notification token.
163 Notification handlers are called after each write transaction is committed,
164 either on the current thread or other threads.
166 Handler blocks are called on the same thread that they were added on, and may
167 only be added on threads which are currently within a run loop. Unless you are
168 specifically creating and running a run loop on a background thread, this will
169 normally only be the main thread.
171 The block has the following definition:
173 typedef void(^RLMNotificationBlock)(RLMNotification notification, RLMRealm *realm);
175 It receives the following parameters:
177 - `NSString` \***notification**: The name of the incoming notification. See
178 `RLMRealmNotification` for information on what
179 notifications are sent.
180 - `RLMRealm` \***realm**: The Realm for which this notification occurred.
182 @param block A block which is called to process Realm notifications.
184 @return A token object which must be retained as long as you wish to continue
185 receiving change notifications.
187 - (RLMNotificationToken *)addNotificationBlock:(RLMNotificationBlock)block __attribute__((warn_unused_result));
189 #pragma mark - Transactions
192 #pragma mark - Writing to a Realm
195 Begins a write transaction on the Realm.
197 Only one write transaction can be open at a time for each Realm file. Write
198 transactions cannot be nested, and trying to begin a write transaction on a
199 Realm which is already in a write transaction will throw an exception. Calls to
200 `beginWriteTransaction` from `RLMRealm` instances for the same Realm file in
201 other threads or other processes will block until the current write transaction
202 completes or is cancelled.
204 Before beginning the write transaction, `beginWriteTransaction` updates the
205 `RLMRealm` instance to the latest Realm version, as if `refresh` had been
206 called, and generates notifications if applicable. This has no effect if the
207 Realm was already up to date.
209 It is rarely a good idea to have write transactions span multiple cycles of
210 the run loop, but if you do wish to do so you will need to ensure that the
211 Realm participating in the write transaction is kept alive until the write
212 transaction is committed.
214 - (void)beginWriteTransaction;
217 Commits all write operations in the current write transaction, and ends the
220 After saving the changes, all notification blocks registered on this specific
221 `RLMRealm` instance are invoked synchronously. Notification blocks registered
222 on other threads or on collections are invoked asynchronously. If you do not
223 want to receive a specific notification for this write tranaction, see
224 `commitWriteTransactionWithoutNotifying:error:`.
226 This method can fail if there is insufficient disk space available to save the
227 writes made, or due to unexpected i/o errors. This version of the method throws
228 an exception when errors occur. Use the version with a `NSError` out parameter
229 instead if you wish to handle errors.
231 @warning This method may only be called during a write transaction.
233 - (void)commitWriteTransaction NS_SWIFT_UNAVAILABLE("");
236 Commits all write operations in the current write transaction, and ends the
239 After saving the changes, all notification blocks registered on this specific
240 `RLMRealm` instance are invoked synchronously. Notification blocks registered
241 on other threads or on collections are invoked asynchronously. If you do not
242 want to receive a specific notification for this write tranaction, see
243 `commitWriteTransactionWithoutNotifying:error:`.
245 This method can fail if there is insufficient disk space available to save the
246 writes made, or due to unexpected i/o errors.
248 @warning This method may only be called during a write transaction.
250 @param error If an error occurs, upon return contains an `NSError` object
251 that describes the problem. If you are not interested in
252 possible errors, pass in `NULL`.
254 @return Whether the transaction succeeded.
256 - (BOOL)commitWriteTransaction:(NSError **)error;
259 Commits all write operations in the current write transaction, without
260 notifying specific notification blocks of the changes.
262 After saving the changes, all notification blocks registered on this specific
263 `RLMRealm` instance are invoked synchronously. Notification blocks registered
264 on other threads or on collections are scheduled to be invoked asynchronously.
266 You can skip notifiying specific notification blocks about the changes made
267 in this write transaction by passing in their associated notification tokens.
268 This is primarily useful when the write transaction is saving changes already
269 made in the UI and you do not want to have the notification block attempt to
270 re-apply the same changes.
272 The tokens passed to this method must be for notifications for this specific
273 `RLMRealm` instance. Notifications for different threads cannot be skipped
276 This method can fail if there is insufficient disk space available to save the
277 writes made, or due to unexpected i/o errors.
279 @warning This method may only be called during a write transaction.
281 @param tokens An array of notification tokens which were returned from adding
282 callbacks which you do not want to be notified for the changes
283 made in this write transaction.
284 @param error If an error occurs, upon return contains an `NSError` object
285 that describes the problem. If you are not interested in
286 possible errors, pass in `NULL`.
288 @return Whether the transaction succeeded.
290 - (BOOL)commitWriteTransactionWithoutNotifying:(NSArray<RLMNotificationToken *> *)tokens error:(NSError **)error;
293 Reverts all writes made during the current write transaction and ends the transaction.
295 This rolls back all objects in the Realm to the state they were in at the
296 beginning of the write transaction, and then ends the transaction.
298 This restores the data for deleted objects, but does not revive invalidated
299 object instances. Any `RLMObject`s which were added to the Realm will be
300 invalidated rather than becoming unmanaged.
301 Given the following code:
303 ObjectType *oldObject = [[ObjectType objectsWhere:@"..."] firstObject];
304 ObjectType *newObject = [[ObjectType alloc] init];
306 [realm beginWriteTransaction];
307 [realm addObject:newObject];
308 [realm deleteObject:oldObject];
309 [realm cancelWriteTransaction];
311 Both `oldObject` and `newObject` will return `YES` for `isInvalidated`,
312 but re-running the query which provided `oldObject` will once again return
315 KVO observers on any objects which were modified during the transaction will
316 be notified about the change back to their initial values, but no other
317 notifcations are produced by a cancelled write transaction.
319 @warning This method may only be called during a write transaction.
321 - (void)cancelWriteTransaction;
324 Performs actions contained within the given block inside a write transaction.
326 @see `[RLMRealm transactionWithBlock:error:]`
328 - (void)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block NS_SWIFT_UNAVAILABLE("");
331 Performs actions contained within the given block inside a write transaction.
333 Write transactions cannot be nested, and trying to execute a write transaction
334 on a Realm which is already participating in a write transaction will throw an
335 exception. Calls to `transactionWithBlock:` from `RLMRealm` instances in other
336 threads will block until the current write transaction completes.
338 Before beginning the write transaction, `transactionWithBlock:` updates the
339 `RLMRealm` instance to the latest Realm version, as if `refresh` had been called, and
340 generates notifications if applicable. This has no effect if the Realm
341 was already up to date.
343 @param block The block containing actions to perform.
344 @param error If an error occurs, upon return contains an `NSError` object
345 that describes the problem. If you are not interested in
346 possible errors, pass in `NULL`.
348 @return Whether the transaction succeeded.
350 - (BOOL)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block error:(NSError **)error;
353 Updates the Realm and outstanding objects managed by the Realm to point to the
356 If the version of the Realm is actually changed, Realm and collection
357 notifications will be sent to reflect the changes. This may take some time, as
358 collection notifications are prepared on a background thread. As a result,
359 calling this method on the main thread is not advisable.
361 @return Whether there were any updates for the Realm. Note that `YES` may be
362 returned even if no data actually changed.
367 Set this property to `YES` to automatically update this Realm when changes
368 happen in other threads.
370 If set to `YES` (the default), changes made on other threads will be reflected
371 in this Realm on the next cycle of the run loop after the changes are
372 committed. If set to `NO`, you must manually call `-refresh` on the Realm to
373 update it to get the latest data.
375 Note that by default, background threads do not have an active run loop and you
376 will need to manually call `-refresh` in order to update to the latest version,
377 even if `autorefresh` is set to `YES`.
379 Even with this property enabled, you can still call `-refresh` at any time to
380 update the Realm before the automatic refresh would occur.
382 Write transactions will still always advance a Realm to the latest version and
383 produce local notifications on commit even if autorefresh is disabled.
385 Disabling `autorefresh` on a Realm without any strong references to it will not
386 have any effect, and `autorefresh` will revert back to `YES` the next time the
387 Realm is created. This is normally irrelevant as it means that there is nothing
388 to refresh (as managed `RLMObject`s, `RLMArray`s, and `RLMResults` have strong
389 references to the Realm that manages them), but it means that setting
390 `RLMRealm.defaultRealm.autorefresh = NO` in
391 `application:didFinishLaunchingWithOptions:` and only later storing Realm
392 objects will not work.
396 @property (nonatomic) BOOL autorefresh;
399 Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
401 The destination file cannot already exist.
403 Note that if this method is called from within a write transaction, the
404 *current* data is written, not the data from the point when the previous write
405 transaction was committed.
407 @param fileURL Local URL to save the Realm to.
408 @param key Optional 64-byte encryption key to encrypt the new file with.
409 @param error If an error occurs, upon return contains an `NSError` object
410 that describes the problem. If you are not interested in
411 possible errors, pass in `NULL`.
413 @return `YES` if the Realm was successfully written to disk, `NO` if an error occurred.
415 - (BOOL)writeCopyToURL:(NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError **)error;
418 Invalidates all `RLMObject`s, `RLMResults`, `RLMLinkingObjects`, and `RLMArray`s managed by the Realm.
420 A Realm holds a read lock on the version of the data accessed by it, so
421 that changes made to the Realm on different threads do not modify or delete the
422 data seen by this Realm. Calling this method releases the read lock,
423 allowing the space used on disk to be reused by later write transactions rather
424 than growing the file. This method should be called before performing long
425 blocking operations on a background thread on which you previously read data
426 from the Realm which you no longer need.
428 All `RLMObject`, `RLMResults` and `RLMArray` instances obtained from this
429 `RLMRealm` instance on the current thread are invalidated. `RLMObject`s and `RLMArray`s
430 cannot be used. `RLMResults` will become empty. The Realm itself remains valid,
431 and a new read transaction is implicitly begun the next time data is read from the Realm.
433 Calling this method multiple times in a row without reading any data from the
434 Realm, or before ever reading any data from the Realm, is a no-op. This method
435 may not be called on a read-only Realm.
439 #pragma mark - Accessing Objects
442 Returns the same object as the one referenced when the `RLMThreadSafeReference` was first created,
443 but resolved for the current Realm for this thread. Returns `nil` if this object was deleted after
444 the reference was created.
446 @param reference The thread-safe reference to the thread-confined object to resolve in this Realm.
448 @warning A `RLMThreadSafeReference` object must be resolved at most once.
449 Failing to resolve a `RLMThreadSafeReference` will result in the source version of the
450 Realm being pinned until the reference is deallocated.
451 An exception will be thrown if a reference is resolved more than once.
453 @warning Cannot call within a write transaction.
455 @note Will refresh this Realm if the source Realm was at a later version than this one.
457 @see `+[RLMThreadSafeReference referenceWithThreadConfined:]`
459 - (nullable id)resolveThreadSafeReference:(RLMThreadSafeReference *)reference
460 NS_REFINED_FOR_SWIFT;
462 #pragma mark - Adding and Removing Objects from a Realm
465 Adds an object to the Realm.
467 Once added, this object is considered to be managed by the Realm. It can be retrieved
468 using the `objectsWhere:` selectors on `RLMRealm` and on subclasses of `RLMObject`.
470 When added, all child relationships referenced by this object will also be added to
471 the Realm if they are not already in it.
473 If the object or any related objects are already being managed by a different Realm
474 an exception will be thrown. Use `-[RLMObject createInRealm:withObject:]` to insert a copy of a managed object
475 into a different Realm.
477 The object to be added must be valid and cannot have been previously deleted
478 from a Realm (i.e. `isInvalidated` must be `NO`).
480 @warning This method may only be called during a write transaction.
482 @param object The object to be added to this Realm.
484 - (void)addObject:(RLMObject *)object;
487 Adds all the objects in a collection to the Realm.
489 This is the equivalent of calling `addObject:` for every object in a collection.
491 @warning This method may only be called during a write transaction.
493 @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`,
494 containing Realm objects to be added to the Realm.
498 - (void)addObjects:(id<NSFastEnumeration>)objects;
501 Adds or updates an existing object into the Realm.
503 The object provided must have a designated primary key. If no objects exist in the Realm
504 with the same primary key value, the object is inserted. Otherwise, the existing object is
505 updated with any changed values.
507 As with `addObject:`, the object cannot already be managed by a different
508 Realm. Use `-[RLMObject createOrUpdateInRealm:withValue:]` to copy values to
511 If there is a property or KVC value on `object` whose value is nil, and it corresponds
512 to a nullable property on an existing object being updated, that nullable property will
515 @warning This method may only be called during a write transaction.
517 @param object The object to be added or updated.
519 - (void)addOrUpdateObject:(RLMObject *)object;
522 Adds or updates all the objects in a collection into the Realm.
524 This is the equivalent of calling `addOrUpdateObject:` for every object in a collection.
526 @warning This method may only be called during a write transaction.
528 @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`,
529 containing Realm objects to be added to or updated within the Realm.
531 @see `addOrUpdateObject:`
533 - (void)addOrUpdateObjects:(id<NSFastEnumeration>)objects;
536 Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
538 @warning This method may only be called during a write transaction.
540 @param object The object to be deleted.
542 - (void)deleteObject:(RLMObject *)object;
545 Deletes one or more objects from the Realm.
547 This is the equivalent of calling `deleteObject:` for every object in a collection.
549 @warning This method may only be called during a write transaction.
551 @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`,
552 containing objects to be deleted from the Realm.
556 - (void)deleteObjects:(id<NSFastEnumeration>)objects;
559 Deletes all objects from the Realm.
561 @warning This method may only be called during a write transaction.
565 - (void)deleteAllObjects;
568 #pragma mark - Migrations
571 The type of a migration block used to migrate a Realm.
573 @param migration A `RLMMigration` object used to perform the migration. The
574 migration object allows you to enumerate and alter any
575 existing objects which require migration.
577 @param oldSchemaVersion The schema version of the Realm being migrated.
579 typedef void (^RLMMigrationBlock)(RLMMigration *migration, uint64_t oldSchemaVersion);
582 Returns the schema version for a Realm at a given local URL.
584 @param fileURL Local URL to a Realm file.
585 @param key 64-byte key used to encrypt the file, or `nil` if it is unencrypted.
586 @param error If an error occurs, upon return contains an `NSError` object
587 that describes the problem. If you are not interested in
588 possible errors, pass in `NULL`.
590 @return The version of the Realm at `fileURL`, or `RLMNotVersioned` if the version cannot be read.
592 + (uint64_t)schemaVersionAtURL:(NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError **)error
593 NS_REFINED_FOR_SWIFT;
596 Performs the given Realm configuration's migration block on a Realm at the given path.
598 This method is called automatically when opening a Realm for the first time and does
599 not need to be called explicitly. You can choose to call this method to control
600 exactly when and how migrations are performed.
602 @param configuration The Realm configuration used to open and migrate the Realm.
603 @return The error that occurred while applying the migration, if any.
607 + (BOOL)performMigrationForConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error;
609 #pragma mark - Unavailable Methods
612 RLMRealm instances are cached internally by Realm and cannot be created directly.
614 Use `+[RLMRealm defaultRealm]`, `+[RLMRealm realmWithConfiguration:error:]` or
615 `+[RLMRealm realmWithURL]` to obtain a reference to an RLMRealm.
617 - (instancetype)init __attribute__((unavailable("Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:.")));
620 RLMRealm instances are cached internally by Realm and cannot be created directly.
622 Use `+[RLMRealm defaultRealm]`, `+[RLMRealm realmWithConfiguration:error:]` or
623 `+[RLMRealm realmWithURL]` to obtain a reference to an RLMRealm.
625 + (instancetype)new __attribute__((unavailable("Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:.")));
628 - (void)addOrUpdateObjectsFromArray:(id)array __attribute__((unavailable("Renamed to -addOrUpdateObjects:.")));
632 // MARK: - RLMNotificationToken
635 A token which is returned from methods which subscribe to changes to a Realm.
637 Change subscriptions in Realm return an `RLMNotificationToken` instance,
638 which can be used to unsubscribe from the changes. You must store a strong
639 reference to the token for as long as you want to continue to receive notifications.
640 When you wish to stop, call the `-invalidate` method. Notifications are also stopped if
641 the token is deallocated.
643 @interface RLMNotificationToken : NSObject
644 /// Stops notifications for the change subscription that returned this token.
647 /// Stops notifications for the change subscription that returned this token.
648 - (void)stop __attribute__((unavailable("Renamed to -invalidate."))) NS_REFINED_FOR_SWIFT;
651 NS_ASSUME_NONNULL_END