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 init(inMemoryIdentifier:)
).
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.
-
Path to the file where this Realm is persisted.
Declaration
Swift
public var path: String { return rlmRealm.path }
-
Indicates if this Realm was opened in read-only mode.
Declaration
Swift
public var readOnly: Bool { return rlmRealm.readOnly }
-
The Schema used by this realm.
Declaration
Swift
public var schema: Schema { return Schema(rlmRealm.schema) }
-
The location of the default Realm as a string. Can be overridden.
~/Library/Application Support/{bundle ID}/default.realm
on OS X.default.realm
in your application’s documents directory on iOS.Declaration
Swift
public class var defaultPath: String
Return Value
Location of the default Realm.
-
Obtains a Realm instance persisted at the specified file path. Defaults to
Realm.defaultPath
Declaration
Swift
public convenience init(path: String = Realm.defaultPath)
Parameters
path
Path to the realm file.
-
Obtains a
Realm
instance with persistence to a specific file path with options.Like
init(path:)
, but with the ability to open read-only realms and get errors as anNSError
inout parameter rather than exceptions.Declaration
Swift
public convenience init?(path: String, readOnly: Bool, encryptionKey: NSData? = nil, error: NSErrorPointer = nil)
Parameters
path
Path to the file you want the data saved in.
readOnly
Bool indicating if this Realm is read-only (must use for read-only files).
encryptionKey
64-byte key to use to encrypt the data.
error
If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, omit the argument, or pass innil
. -
Obtains a Realm instance for an un-persisted in-memory Realm. The identifier used to create this instance can be used to access the same in-memory Realm from multiple threads.
Because in-memory Realms are not persisted, you must be sure to hold on to a reference to the
Realm
object returned from this for as long as you want the data to last. Realm’s internal cache ofRealm
s will not keep the in-memory Realm alive across cycles of the run loop, so without a strong reference to theRealm
a new Realm will be created each time. Note thatObject
s,List
s, andResults
that refer to objects persisted in a Realm have a strong reference to the relevantRealm
, as doNotifcationToken
s.Declaration
Swift
public convenience init(inMemoryIdentifier: String)
Parameters
identifier
A string used to identify a particular in-memory Realm.
-
Helper to perform actions contained within the given block inside a write transation.
Declaration
Swift
public func write(block: (() -> Void))
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 with 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.
After this is called, the
Realm
reverts back to being read-only.Calling this when not in a write transaction will throw an exception.
Declaration
Swift
public func commitWrite()
-
Revert 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 reinstate deleted accessor objects. 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.
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 linked (child) objects referenced by this object will also be added to the Realm if they are not already in it. If the object or any linked 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.
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 object.Creates or updates an instance of this object and adds it to the
Realm
populating the object represented by 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.
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 an
Array
, 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.
Declaration
Swift
public func delete(object: Object)
Parameters
object
The object to be deleted.
-
Deletes the given objects from this Realm.
Declaration
Swift
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S)
Parameters
object
The objects to be deleted. This can be a
List
,Results
, or any other enumerable SequenceType which generates Object. -
Deletes all objects from this Realm.
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.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.
Declaration
Swift
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken
Parameters
block
A block which is called to process Realm notifications. It receives the following parameters:
Notification
: The incoming notification.Realm
: The realm for which this notification occurred.
Return Value
A notification token which can later be passed to
removeNotification(_:)
to remove this notification. -
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 call -refresh on the Realm to update it to get the latest version.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
-
Update a
Realm
and outstanding objects to point to the most recent data for thisRealm
.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.
Declaration
Swift
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) -> NSError?
Parameters
path
Path to save the Realm to.
encryptionKey
Optional 64-byte encryption key to encrypt the new file with.
Return Value
If an error occurs, returns an
NSError
object, otherwisenil
.Whether the realm was copied successfully.
-
Set the encryption key to use when opening Realms at a certain path.
This can be used as an alternative to explicitly passing the key to
Realm(path:, encryptionKey:, readOnly:, error:)
each time a Realm instance is needed. The encryption key will be used any time a Realm is opened withRealm(path:)
orRealm()
.If you do not want Realm to hold on to your encryption keys any longer than needed, then use
Realm(path:, encryptionKey:, readOnly:, error:)
rather than this method.Declaration
Swift
public class func setEncryptionKey(encryptionKey: NSData?, forPath: String = Realm.defaultPath)
Parameters
encryptionKey
64-byte encryption key to use, or
nil
to unset.path
Realm path to set the encryption key for.