Navigation

Read & Write Data - iOS SDK

On this page

The examples on this page use the following models:

A filter selects a subset of results based on the value(s) of one or more object properties. Realm Database provides a full-featured query engine that you can use to define filters.

Tip
Filter on Related and Embedded Object Properties

To filter a query based on a property of an embedded object or a related object, use dot-notation as if it were in a regular, nested object.

The types in your predicate must match the types of the properties. Avoid comparing ObjectId properties to strings, as Realm Database does not automatically convert strings to ObjectIds.

The following example shows the correct and incorrect way to write a query with an ObjectId given the following Realm object:

class User: Object {
@Persisted var id: ObjectId
@Persisted var name = ""
}
let realm = try! Realm()
let users = realm.objects(User.self)
// Get specific user by ObjectId id
let specificUser = users.filter("id = %@", ObjectId("11223344556677889900aabb")).first
// WRONG: Realm will not convert the string to an object id
// users.filter("id = '11223344556677889900aabb'") // not ok
// users.filter("id = %@", "11223344556677889900aabb") // not ok

A sort operation allows you to configure the order in which Realm Database returns queried objects. You can sort based on one or more properties of the objects in the results collection. Realm Database only guarantees a consistent order of results if you explicitly sort them.

Tip
Sort on Related and Embedded Object Properties

To sort a query based on a property of an embedded object or a related object, use dot-notation as if it were in a regular, nested object.

Note

String sorting and case-insensitive queries are only supported for character sets in 'Latin Basic', 'Latin Supplement', 'Latin Extended A', and 'Latin Extended B' (UTF-8 range 0-591).

You can query through a relationship the same way you would access a member of a regular Swift or Objective-C object.

You can query through an inverse relationship the same way you would access a member of a regular Swift or Objective-C object.

You can use Realm's aggregation operators for sophisticated queries against list properties.

Because results are lazily evaluated, you can chain several queries together. Unlike traditional databases, this does not require a separate trip to the database for each successive query.

Example

To get a result set for tan dogs, and tan dogs whose names start with ‘B’, chain two queries like this:

You can initialize an object by passing an initializer value to Object.init(value:). The initializer value can be a key-value coding compliant object, a dictionary, or an array containing one element for each managed property.

Note

When using an array as an initializer value, you must include all properties in the same order as they are defined in the model.

You can even initialize related or embedded objects by nesting initializer values:

Realm does not directly support JSON, but you can use JSONSerialization.jsonObject(with:options:) to convert JSON into a value that you can pass to Realm.create(_:value:update:).

Nested objects or arrays in the JSON map to to-one or to-many relationships.

The JSON property names and types must match the destination object schema exactly. For example:

  • float properties must be initialized with float-backed NSNumbers.
  • Date and Data properties cannot be inferred from strings. Convert them to the appropriate type before passing to Realm.create(_:value:update:).
  • Required properties cannot be null or missing in the JSON.

Realm ignores any properties in the JSON not defined in the object schema.

Tip

If your JSON schema doesn't exactly align with your Realm objects, consider using a third-party framework to transform your JSON. There are many model mapping frameworks that work with Realm. See a partial list in the realm-cocoa repository.

Important

The create methods do not support handling cyclical object graphs. Do not pass in an object containing relationships involving objects that refer back to their parents, either directly or indirectly.

You can modify properties of a Realm object inside of a write transaction in the same way that you would update any other Swift or Objective-C object.

Tip
Update Related and Embedded Objects

To update a property of an embedded object or a related object, modify the property with dot-notation or bracket-notation as if it were in a regular, nested object.

Object, Result, and List all conform to key-value coding. This can be useful when you need to determine which property to update at runtime.

Applying KVC to a collection is a great way to update objects in bulk. Avoid the overhead of iterating over a collection while creating accessors for every item.

let realm = try! Realm()
let allDogs = realm.objects(Dog.self)
try! realm.write {
allDogs.first?.setValue("Sparky", forKey: "name")
// Move the dogs to Toronto for vacation
allDogs.setValue("Toronto", forKey: "currentCity")
}
Tip

You can also add values for embedded objects or relationships this way. See Initialize Objects with a Value.

An upsert either inserts or updates an object depending on whether the object already exists. Upserts require the data model to have a primary key.

You can also partially update an object by passing the primary key and a subset of the values to update:

Important
Do not use objects after delete

You cannot access or modify an object after you have deleted it from a realm. If you try to use a deleted object, Realm Database throws an error.

Give Feedback

On this page