I’m trying to figure out how to properly use nested optional objects with realm swift, to update parent view when nested object change.
In this code, Person is the parent object that has a Dog as a nested object. ContentView displays the person’s name and dog’s age, and DogView is used to change the dog’s age using a Stepper.
When the dog’s age is updated in DogView, I want this change to be reflected in ContentView. However, the change in the nested object’s property doesn’t seem to be triggering a refresh of the parent view.
Any help appreciated, tried without luck with using $person.dog and also explored realm projections.
Models
class Person: Object, ObjectKeyIdentifiable {
@Persisted var name: String
@Persisted var dog: Dog?
convenience init(name: String) {
self.init()
self.name = name
self.dog = Dog(name: "Fido", age: 5)
}
}
class Dog: Object, ObjectKeyIdentifiable {
@Persisted var name: String
@Persisted var age: Int
convenience init(name: String, age: Int) {
self.init()
self.name = name
self.age = age
}
}
Views
struct ContentView: View {
@Environment(\.realm) var realm
@ObservedRealmObject var person: Person
@State private var showSheet = false
var body: some View {
NavigationView {
Form {
Text("Person's Name: \(person.name)")
if let dog = person.dog {
Button(action: {
showSheet = true
}) {
Text("Dog's Age: \(dog.age)")
}
.sheet(isPresented: $showSheet) {
DogView(dog: dog)
}
}
}
}
}
}
struct DogView: View {
@ObservedRealmObject var dog: Dog
var body: some View {
Stepper("Age: \(dog.age)", value: $dog.age, in: 0...20)
}
}