Reputation: 4308
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?
Upvotes: 1
Views: 98
Reputation: 257543
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
Upvotes: 3