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) } -
Returns a
Configurationthat can be used to create thisRealminstance.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 } -
The location of the default Realm as a string. Can be overridden.
~/Library/Application Support/{bundle ID}/default.realmon OS X.default.realmin your application’s documents directory on iOS.Declaration
Swift
public class var defaultPath: StringReturn Value
Location of the default Realm.
-
Obtains a Realm instance with the given configuration. Defaults to the default Realm configuration, which can be changed by setting
Realm.Configuration.defaultConfiguration.Declaration
Swift
public convenience init(configuration: Configuration = Configuration.defaultConfiguration) throwsParameters
configurationThe configuration to use when creating the Realm instance.
-
Obtains a Realm instance persisted at the specified file path.
Declaration
Swift
public convenience init(path: String) throwsParameters
pathPath to the realm file.
-
Obtains a
Realminstance with persistence to a specific file path with options.Like
init(path:), but with the ability to open read-only realms and encrypted realms.Declaration
Swift
public convenience init(path: String, readOnly: Bool, encryptionKey: NSData? = nil) throwsParameters
pathPath to the file you want the data saved in.
readOnlyBool indicating if this Realm is read-only (must use for read-only files).
encryptionKey64-byte key to use to encrypt the data.
-
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
Realmobject returned from this for as long as you want the data to last. Realm’s internal cache ofRealms will not keep the in-memory Realm alive across cycles of the run loop, so without a strong reference to theRealma new Realm will be created each time. Note thatObjects,Lists, andResultsthat refer to objects persisted in a Realm have a strong reference to the relevantRealm, as doNotifcationTokens.Declaration
Swift
public convenience init(inMemoryIdentifier: String) throwsParameters
identifierA 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)) throwsParameters
blockThe 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
Realmwhich is already in a write transaction with throw an exception. Calls tobeginWritefromRealminstances in other threads will block until the current write transaction completes.Before beginning the write transaction,
beginWriteupdates theRealmto the latest Realm version, as ifrefresh()was called, and generates notifications if applicable. This has no effect if theRealmwas 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
Realmin 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
Realmreverts back to being read-only.Calling this when not in a write transaction will throw an exception.
Declaration
Swift
public func commitWrite() throws -
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
Objects 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
oldObjectandnewObjectwill returntrueforinvalidated, but re-running the query which providedoldObjectwill 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
createfunctions 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.
invalidatedmust be false).Declaration
Swift
public func add(object: Object, update: Bool = false)Parameters
objectObject to be added to this Realm.
updateIf 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
objectsA sequence which contains objects to be added to this Realm.
updateIf true will try to update existing objects with the same primary key.
-
Create an
Objectwith the given value.Creates or updates an instance of this object and adds it to the
Realmpopulating 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.
Declaration
Swift
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> TParameters
typeThe object type to create.
valueThe 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 anArraywith 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.updateIf 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
objectThe 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
objectsThe 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.
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
typeThe 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
nilif 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
typeThe type of the objects to be returned.
keyThe primary key of the desired object.
Return Value
An object of type
typeornilif 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) -> NotificationTokenParameters
blockA block which is called to process Realm notifications. It receives the following parameters:
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
notificationTokenThe 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
Realmwithout any strong references to it will not have any effect, and it will switch back to YES the next time theRealmobject is created. This is normally irrelevant as it means that there is nothing to refresh (as persistedObjects,Lists, andResultshave strong references to the containingRealm), but it means that settingRealm().autorefresh = falseinapplication(_:didFinishLaunchingWithOptions:)and only later storing Realm objects will not work.Defaults to true.
Declaration
Swift
public var autorefresh: Bool -
Update a
Realmand outstanding objects to point to the most recent data for thisRealm.Declaration
Swift
public func refresh() -> BoolReturn Value
Whether the realm had any updates. Note that this may return true even if no data has actually changed.
-
Invalidate all
Objects andResultsread 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,ResultsandListinstances obtained from thisRealmon the current thread are invalidated, and can not longer be used. TheRealmitself 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) throwsParameters
pathPath to save the Realm to.
encryptionKeyOptional 64-byte encryption key to encrypt the new file with.
-
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 path: String = Realm.defaultPath)Parameters
encryptionKey64-byte encryption key to use, or
nilto unset.pathRealm path to set the encryption key for.
View on GitHub
Install in Dash
Realm Class Reference