Hi guys,
I am trying to use the new @Observable
macro. According to the documentation, this new macro will automatically generate observable properties, but I am having issues using my properties when Bindings
are necessary.
Previously I had a setup like this:
class Example: ObservableObject {
@Published public var myArray = [CustomType]()
}
I initialised one instance of the Example-class
in @main
@StateObject private var exampleClass = Example()
And added as an .environmentObject
onto the root view
ContentView()
.environmentObject(exampleClass)
In child views I was able to access the @Published
property as a binding via
@EnvironmentObject private var example: Example
$example.myArray
What I am trying now
This is the setup that I am trying with now:
@Observable class Example {
public var myArray = [CustomType]()
}
State
instead of StateObject
in @main
@State private var exampleClass = Example()
.environment
instead of .environmentObject
ContentView()
.environmentObject(exampleClass)
@Environment
instead of @EnvironmentObject
@Environment(Example.self) private var example
This new setup is not letting me access $example.myArray
. Is this intended? Could someone explain why?