ImShrey
ImShrey

Reputation: 418

Does realm need nested objects to be added explicitly

Consider two models:

class Person: Object {
    @objc dynamic var name: String
    @objc dynamic var pet: Animal
}

class Animal: Object {
    @objc dynamic var name: String
}

Now if I had to create and add new Person with a Pet. Is following is sufficient?

realm.write{
    let dog = Animal(name: "Daisy")
    let person = Person(name: "John Wick", pet: dog)
    
    realm.add(person)     // <----- This

}

Or I need to explicitly add dog(Nested Object) too?

realm.write{
    let dog = Animal(name: "Daisy")
    let person = Person(name: "John Wick", pet: dog)
    
    realm.add(person)
    realm.add(dog)     // <----- Like This

}

Upvotes: 2

Views: 507

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

This is sufficient

realm.write{
    let dog = Animal(name: "Daisy")
    let person = Person(name: "John Wick", pet: dog)
    
    realm.add(person)     // <----- This

} 

The Animal object will be inserted automatically , just make a query for that model and you will get it

Upvotes: 3

Related Questions