bcorrel2
bcorrel2

Reputation: 11

SwiftUI Observable Object Not Observed

In my latest project to learn SwiftUI, I create an Observable Object in a file called UserData:

final class UserData: ObservableObject {
    @Published var data = jsonData
}

I set the Environmental Variable in SceneDelgate:

window.rootViewController = UIHostingController(rootView: dataList().environmentObject(UserData()))

And declare it in the relevant file:

@EnvironmentObject private var userData: UserData

    var body: some View {
        NavigationView {
            List {
                ForEach(userData.data) { data in
                    DataRow(data: data)
                }
            }
        }
            .navigationBarTitle(Text("My Data"))
    }

Yet I get this:

"Can Not Preview File, Data.app may have crashed"

Checking the crash report, it appears my code can't find UserData. However, I believe I have taken all the steps necessary to make it observable (as this is basically copy and pasted from an Apple tutorial). What's going wrong?

Upvotes: 1

Views: 778

Answers (2)

Tobias Hesselink
Tobias Hesselink

Reputation: 1647

When using EnvironmentObject and you want to test in the live preview, you need to set the object manually like this:

struct dataList_Previews: PreviewProvider {
    static var previews: some View {
        dataList().environmentObject(UserData()) // Your env object
    }
}

Upvotes: 1

Ernist Isabekov
Ernist Isabekov

Reputation: 1233

I think it might be crash in your real time preview

  struct dataList_Previews: PreviewProvider {
    static var previews: some View {
        dataList().environmentObject(UserData())
    }
}

Upvotes: 0

Related Questions