简体   繁体   中英

@EnvironmentObject not created correctly

I want to access an instance of the class

class MyModel: ObservableObject {
  @Published var s: String = "test"
}

via the environment. I instanciated it in Scene Delegate

  var m = MyModel()

Then I tried to put it into the environment with

let contentView = ContentView().environment(\.managedObjectContext, context)
_ = contentView.environmentObject(m)

In contentview I reference it like

@EnvironmentObject var mod: MyModel

If I access it like

Text(mod.s)

the app crashes, saying "Fatal error: No ObservableObject of type MyModel found."

What am I doing wrong?

Instead of

let contentView = ContentView().environment(\\.managedObjectContext, context) _ = contentView.environmentObject(m)

use

let contentView = ContentView()
                    .environmentObject(m)
                    .environment(\.managedObjectContext, context)

it is not a setter, it is view modifier that generates another view with injected environment object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM