Realm
public final class 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 (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm 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
Realm instances are not thread safe and can not be shared across threads or dispatch queues. You must construct a new instance 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.-
Path to the file where this Realm is persisted.
Declaration
Swift
public var path: String { return configuration.path! }
-
Indicates if this Realm was opened in read-only mode.
Declaration
Swift
public var readOnly: Bool { return configuration.readOnly }
-
The Schema used by this realm.
Declaration
Swift
public var schema: Schema { return Schema(rlmRealm.schema) }
-
Returns the
Configuration
that was used to create thisRealm
instance.Declaration
Swift
public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
-
Indicates if this Realm contains any objects.
Declaration
Swift
public var isEmpty: Bool { return rlmRealm.isEmpty }
-
Obtains a Realm instance with the default Realm configuration, which can be changed by setting
Realm.Configuration.defaultConfiguration
.Throws
An NSError if the Realm could not be initialized.Declaration
Swift
public convenience init() throws
-
Obtains a Realm instance with the given configuration.
Throws
An NSError if the Realm could not be initialized.
Declaration
Swift
public convenience init(configuration: Configuration) throws
Parameters
configuration
The configuration to use when creating the Realm instance.
-
Obtains a Realm instance persisted at the specified file path.
Throws
An NSError if the Realm could not be initialized.
Declaration
Swift
public convenience init(path: String) throws
Parameters
path
Path to the realm file.
-
Obtains a Realm instance persisted at the specified file URL.
Throws
An NSError if the Realm could not be initialized.
Declaration
Swift
public convenience init(fileURL: NSURL) throws
Parameters
fileURL
Local URL to the realm file.
-
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 in a write transaction will throw an exception. Calls towrite
fromRealm
instances in other threads will block until the current write transaction completes.Before executing the write transaction,
write
updates theRealm
to the latest Realm version, as ifrefresh()
was called, and generates notifications if applicable. This has no effect if theRealm
was already up to date.Throws
An NSError if the transaction could not be written.
Declaration
Swift
public func write(@noescape block: (() -> Void)) throws
Parameters
block
The block to be executed inside a write transaction.
-
Begins a write transaction in a
Realm
.Only one write transaction can be open at a time. 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 tobeginWrite
fromRealm
instances in other threads will block until the current write transaction completes.Before beginning the write transaction,
beginWrite
updates theRealm
to the latest Realm version, as ifrefresh()
was called, and generates notifications if applicable. This has no effect if theRealm
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
in the write transaction is kept alive until the write transaction is committed.Declaration
Swift
public func beginWrite()
-
Commits all writes operations in the current write transaction, and ends the transaction.
Calling this when not in a write transaction will throw an exception.
Throws
An NSError if the transaction could not be written.Declaration
Swift
public func commitWrite() throws
-
Reverts all writes made in the current write transaction and end 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
Object
s which were added to the Realm will be invalidated rather than switching back to standalone objects. Given the following code:let oldObject = objects(ObjectType).first! let newObject = ObjectType() realm.beginWrite() realm.add(newObject) realm.delete(oldObject) realm.cancelWrite()
Both
oldObject
andnewObject
will returntrue
forinvalidated
, but re-running the query which providedoldObject
will once again return the valid object.Calling this when not in a write transaction will throw an exception.
Declaration
Swift
public func cancelWrite()
-
Indicates if this Realm is currently in a write transaction.
Warning
Wrapping mutating operations in a write transaction if this property returnsfalse
may 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
Swift
public var inWriteTransaction: Bool
-
Adds or updates an object to be persisted it in this Realm.
When ‘update’ is ‘true’, the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.
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 one of the
create
functions 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.
invalidated
must be false).Declaration
Swift
public func add(object: Object, update: Bool = false)
Parameters
object
Object to be added to this Realm.
update
If true will try to update existing objects with the same primary key.
-
Adds or updates objects in the given sequence to be persisted it in this Realm.
See
add(_:update:)
Warning
This method can only be called during a write transaction.
Declaration
Swift
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false)
Parameters
objects
A sequence which contains objects to be added to this Realm.
update
If true will try to update existing objects with the same primary key.
-
Create an
Object
with the given value.Creates or updates an instance of this object and adds it to the
Realm
populating the object with the given value.When ‘update’ is ‘true’, the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.
Warning
This method can only be called during a write transaction.
Declaration
Swift
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T
Parameters
type
The object type to create.
value
The value used to populate the object. This can be any key/value coding compliant object, or a JSON dictionary such as those returned from the methods in
NSJSONSerialization
, or anArray
with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. When passing in anArray
, all properties must be present, valid and in the same order as the properties defined in the model.update
If true will try to update existing objects with the same primary key.
Return Value
The created object.
-
Deletes the given object from this Realm.
Warning
This method can only be called during a write transaction.
Declaration
Swift
public func delete(object: Object)
Parameters
object
The object to be deleted.
-
Deletes the given objects from this Realm.
Warning
This method can only be called during a write transaction.
Declaration
Swift
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S)
Parameters
objects
The objects to be deleted. This can be a
List<Object>
,Results<Object>
, or any other enumerable SequenceType which generates Object. -
Deletes all objects from this Realm.
Warning
This method can only be called during a write transaction.Declaration
Swift
public func deleteAll()
-
Returns all objects of the given type in the Realm.
Declaration
Swift
public func objects<T: Object>(type: T.Type) -> Results<T>
Parameters
type
The type of the objects to be returned.
Return Value
All objects of the given type in Realm.
-
Get an object with the given primary key.
Returns
nil
if no object exists with the given primary key.This method requires that
primaryKey()
be overridden on the given subclass.See
Object.primaryKey()
Declaration
Swift
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T?
Parameters
type
The type of the objects to be returned.
key
The primary key of the desired object.
Return Value
An object of type
type
ornil
if an object with the given primary key does not exist.
-
Add a notification handler for changes in this Realm.
Notification handlers are called after each write transaction is committed, independent from the thread or process.
The block is called on the same thread as it was 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.
Notifications can’t be delivered as long as the runloop 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 continue to be sent to the block. To stop receiving updates, call stop() on the token.
Declaration
Swift
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken
Parameters
block
A block which is called to process Realm notifications. It receives the following parameters:
Return Value
A token which must be held for as long as you want notifications to be delivered.
-
Remove a previously registered notification handler using the token returned from
addNotificationBlock(_:)
Declaration
Swift
public func removeNotification(notificationToken: NotificationToken)
Parameters
notificationToken
The token returned from
addNotificationBlock(_:)
corresponding to the notification block to remove.
-
Whether this Realm automatically updates 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 version.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 totrue
.Even with this 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 this is enabled.
Disabling this on a
Realm
without any strong references to it will not have any effect, and it will switch back to YES the next time theRealm
object is created. This is normally irrelevant as it means that there is nothing to refresh (as persistedObject
s,List
s, andResults
have strong references to the containingRealm
), but it means that settingRealm().autorefresh = false
inapplication(_:didFinishLaunchingWithOptions:)
and only later storing Realm objects will not work.Defaults to true.
Declaration
Swift
public var autorefresh: Bool
-
Declaration
Swift
public func refresh() -> Bool
Return Value
Whether the realm had any updates. Note that this may return true even if no data has actually changed.
-
Invalidate all
Object
s andResults
read from this 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
,Results
andList
instances obtained from thisRealm
on the current thread are invalidated, and can not longer be used. TheRealm
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 cannot be called on a read-only Realm.
Declaration
Swift
public func invalidate()
-
Write an encrypted and compacted copy of the Realm to the given path.
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.
Throws
An NSError if the copy could not be written.
Declaration
Swift
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) throws
Parameters
path
Path to save the Realm to.
encryptionKey
Optional 64-byte encryption key to encrypt the new file with.
-
Write an encrypted and compacted copy of the Realm 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.
Throws
An NSError if the copy could not be written.
Declaration
Swift
public func writeCopyToURL(fileURL: NSURL, encryptionKey: NSData? = nil) throws
Parameters
fileURL
Local URL to save the Realm to.
encryptionKey
Optional 64-byte encryption key to encrypt the new file with.
-
A
Realm.Configuration
is used to describe the different options used to create aRealm
instance.
See moreRealm.Configuration
instances are just plain Swift structs, and unlikeRealm
andObject
s can be freely shared between threads. Creating configuration objects for class subsets (by setting theobjectTypes
property) can be expensive, and so you will normally want to cache and reuse a single configuration object for each distinct configuration that you are using rather than creating a new one each time you open aRealm
.Declaration
Swift
public struct Configuration
-
Returns a human-readable description of the configuration.
Declaration
Swift
public var description: String