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 (for example, by using the same
path or identifier) produces limited overhead.
If you specifically want to ensure a Realm
instance 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 cannot be shared across threads or dispatch queues. You must
construct a new instance for each thread in which a Realm will be accessed. For dispatch queues, this means
that you must construct a new instance in each block which is dispatched, as a queue is not guaranteed to
run all of its blocks on the same thread.
-
The
Schema
used by the Realm.Declaration
Swift
public var schema: Schema { return Schema(rlmRealm.schema) }
-
The
RealmConfiguration
object 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 an instance of the default Realm.
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
Configuration
, which can be changed by setting a newConfiguration
object on theRealm.Configuration.defaultConfiguration
property.Throws
AnNSError
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
A configuration value to use when creating the Realm.
-
Obtains a
Realm
instance persisted at a specified file URL.Throws
An
NSError
if the Realm could not be initialized.Declaration
Swift
public convenience init(fileURL: NSURL) throws
Parameters
fileURL
The local URL of the file the Realm should be saved at.
-
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 participating in a write transaction will throw an error. Calls to
write
fromRealm
instances in other threads will block until the current write transaction completes.Before executing the write transaction,
write
updates theRealm
instance to the latest Realm version, as ifrefresh()
had been called, and generates notifications if applicable. This has no effect if the Realm was already up to date.Throws
An
NSError
if the transaction could not be completed successfully.Declaration
Swift
public func write(@noescape block: (() -> Void)) throws
Parameters
block
The block containing actions to perform.
-
Begins a write transaction on the 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 error. Calls to
beginWrite
fromRealm
instances in other threads will block until the current write transaction completes.Before beginning the write transaction,
beginWrite
updates theRealm
instance to the latest Realm version, as ifrefresh()
had been called, and generates notifications if applicable. This has no effect if the Realm 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 write operations in the current write transaction, and ends the transaction.
Warning
This method may only be called during a write transaction.
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 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
Object
s which were added to the Realm will be invalidated rather than becoming unmanaged. 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.Warning
This method may only be called during a write transaction.Declaration
Swift
public func cancelWrite()
-
Indicates whether 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 existing object into the Realm.
Only pass
true
toupdate
if the object has a primary key. If no objects exist in the Realm 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 are already being managed by a different Realm an error will be thrown. Use one of the
create
functions to insert a copy of a managed 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 befalse
).Declaration
Swift
public func add(object: Object, update: Bool = false)
Parameters
object
The object to be added to this Realm.
update
If
true
, the Realm will try to find an existing copy of the object (with the same primary key), and update it. Otherwise, the object will be added. -
Adds or updates all the objects in a collection into the Realm.
See
Warning
This method may 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 the Realm.
update
If
true
, objects that are already in the Realm will be updated instead of added anew. -
Creates or updates a Realm object with a given value, adding it to the Realm and returning it.
Only pass
true
toupdate
if the object has a primary key. If no objects exist in the Realm with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.Warning
This method may 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 type of the object to create.
value
The value used to populate the object. This can be any key-value coding compliant object, or an array or dictionary returned from the methods in
NSJSONSerialization
, or anArray
containing one element for each persisted property. An error will be thrown if any required properties are not present and those properties were not defined with default values.update
If
true
, the Realm will try to find an existing copy of the object (with the same primary key), and update it. Otherwise, the object will be added.Return Value
The newly created object.
-
Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
Warning
This method may only be called during a write transaction.
Declaration
Swift
public func delete(object: Object)
Parameters
object
The object to be deleted.
-
Deletes one or more objects from the Realm.
Warning
This method may 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 enumerableSequenceType
whose elements areObject
s. -
Deletes all objects from the Realm.
Warning
This method may only be called during a write transaction.Declaration
Swift
public func deleteAll()
-
Returns all objects of the given type stored 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
A
Results
containing the objects. -
Retrieves the single instance of a given object type with the given primary key from the Realm.
This method requires that
primaryKey()
be overridden on the given object class.Declaration
Swift
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T?
Parameters
type
The type of the object to be returned.
key
The primary key of the desired object.
Return Value
An object of type
type
, ornil
if no instance with the given primary key exists.
-
Adds a notification handler for changes in this Realm, and returns a notification token.
Notification handlers are called after each write transaction is committed, independent from the thread or process.
Handler blocks are called on the same thread that they were added on, and may 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 will normally only be the main thread.
Notifications can’t be delivered as long as the run loop 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.Notification
: The incoming notification.Realm
: The Realm for which this notification occurred.
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 retained for as long as you wish to continue receiving change notifications.
-
Set this property to
true
to automatically update this Realm 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 data.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 automatic refreshing is enabled.
Disabling
autorefresh
on aRealm
without any strong references to it will not have any effect, andautorefresh
will revert back totrue
the next time the Realm 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 theRealm
that manages them), 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
-
Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
Declaration
Swift
public func refresh() -> Bool
Return Value
Whether there were any updates for the Realm. Note that
true
may be returned even if no data actually changed.
-
Invalidates all
Object
s andResults
managed by the 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
instance on the current thread are invalidated.Object
s andArray
s cannot be used.Results
will become empty. The Realm 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 may not be called on a read-only Realm.
Declaration
Swift
public func invalidate()
-
Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
The destination file cannot already exist.
Note that if this method is called from within a write transaction, the current data is written, not the data from the point when the previous 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
Configuration
instance describes the different options used to create an instance of a Realm.Configuration
instances are just plain Swift structs. UnlikeRealm
s andObject
s, they can be freely shared between threads as long as you do not mutate them.Creating configuration values for class subsets (by setting the
See moreobjectClasses
property) can be expensive. Because of this, you will normally want to cache and reuse a single configuration value for each distinct configuration rather than creating a new value each time you open a Realm.Declaration
Swift
public struct Configuration
-
Returns a human-readable description of the configuration.
Declaration
Swift
public var description: String