Navigation

Embedded Objects - iOS SDK

An embedded object is a special type of Realm object that models complex data about a specific object. Embedded objects are similar to relationships, but they provide additional constraints and map more naturally to the denormalized MongoDB document model.

Realm enforces unique ownership constraints that treat each embedded object as nested data inside of a single, specific parent object. An embedded object inherits the lifecycle of its parent object and cannot exist as an independent Realm object. Realm automatically deletes embedded objects if their parent object is deleted or when overwritten by a new embedded object instance.

Note
Realm Uses Cascading Deletes for Embedded Objects

When you delete a Realm object, Realm automatically deletes any embedded objects referenced by that object. Any objects that your application must persist after the deletion of their parent object should use relationships instead.

Embedded object types are reusable and composable. You can use the same embedded object type in multiple parent object types and you can embed objects inside of other embedded objects.

Important

Embedded objects cannot have a primary key.

To define an embedded object, derive a class from EmbeddedObject in Swift or RLMEmbeddedObject in Objective-C. You can reference an embedded object type from parent object types in the same way as you would define a relationship:

// Define an embedded object
class Address: EmbeddedObject {
@objc dynamic var street: String?
@objc dynamic var city: String?
@objc dynamic var country: String?
@objc dynamic var postalCode: String?
}
// Define an object with one embedded object
class Contact: Object {
@objc dynamic var _id = ObjectId.generate()
@objc dynamic var name = ""
// Embed a single object.
// Embedded object properties must be marked optional.
@objc dynamic var address: Address?
override static func primaryKey() -> String? {
return "_id"
}
convenience init(name: String, address: Address) {
self.init()
self.name = name
self.address = address
}
}
// Define an object with an array of embedded objects
class Business: Object {
@objc dynamic var name = ""
let addresses = List<Address>() // Embed an array of objects
convenience init(name: String, addresses: [Address]) {
self.init()
self.name = name
self.addresses.append(objectsIn: addresses)
}
}

To create an embedded object, assign an instance of the embedded object to a parent object's property:

// Open the default realm
let realm = try! Realm()
try! realm.write {
let address = Address()
address.street = "123 Fake St"
address.city = "Springfield"
address.country = "USA"
address.postalCode = "90710"
let contact = Contact(name: "Nick Riviera", address: address)
realm.add(contact)
}

To update a property in an embedded object, modify the property in a write transaction:

// Open the default realm
let realm = try! Realm()
let idOfContactToUpdate = ObjectId("5f47f4811060b1aa6cc71272")
// Find the contact to update by ID
guard let contact = realm.object(ofType: Contact.self, forPrimaryKey: idOfContactToUpdate) else {
print("Contact \(idOfContactToUpdate) not found")
return
}
try! realm.write {
// Update the embedded object directly through the contact
contact.address?.street = "Hollywood Upstairs Medical College"
contact.address?.city = "Los Angeles"
contact.address?.postalCode = "90210"
print("Updated contact: \(contact)")
}

To overwrite an embedded object, reassign the embedded object property of a party to a new instance in a write transaction:

// Open the default realm
let realm = try! Realm()
let idOfContactToUpdate = ObjectId("5f47f4811060b1aa6cc71272")
// Find the contact to update by ID
guard let contact = realm.object(ofType: Contact.self, forPrimaryKey: idOfContactToUpdate) else {
print("Contact \(idOfContactToUpdate) not found")
return
}
try! realm.write {
let newAddress = Address()
newAddress.street = "Hollywood Upstairs Medical College"
newAddress.city = "Los Angeles"
newAddress.country = "USA"
newAddress.postalCode = "90210"
// Overwrite the embedded object
contact.address = newAddress
print("Updated contact: \(contact)")
}

Use dot notation to filter or sort a collection of objects based on an embedded object property value:

Note

It is not possible to query embedded objects directly. Instead, access embedded objects through a query for the parent object type.

// Open the default realm
let realm = try! Realm()
// Get all contacts in Los Angeles, sorted by street address
let losAngelesContacts = realm.objects(Contact.self)
.filter("address.city = %@", "Los Angeles")
.sorted(byKeyPath: "address.street")
print("Los Angeles Contacts: \(losAngelesContacts)")
Give Feedback