Search code examples
iosswiftuirealm

StateObject property doesn't update view but ObservedObject does


I am saving data to Realm DB in another View where I use @EnvironmentObject var modelData : DBViewModel and loading them in this View

struct SelectedSinsList: View {
@StateObject var modelData = DBViewModel() //@ObservedObject works, as it always recreates the List when I open this view and values are updated
var body: some View {
    NavigationView {
        ScrollView{
            VStack(spacing: 15){
                ForEach(modelData.sins){sin in //..........

Solution

  • That behavior indicates that the only reason your view is updating with new data is that a parent view is redrawing, thus triggering the "unowned" observed object to be rebuilt.

    State and StateObject outlast the View struct’s body being invalidated and redrawn. To use those, you’ll need to connect the callback or publisher in the StateObject to its objectWillChange publisher by calling self.objectWillChange.send()

    But if that DBViewModel is already an environmentObject, why recreate it?