Reputation: 33
I have an observed object in my ContentView which contains tabviews.
class GlobalValue: ObservableObject {
@Published var stringValue = ""
@Published var intValue = 0
}
struct ContentView: View {
@ObservedObject var globalValue = GlobalValue()
}
From one of the tabs I need to change ContentView's observed object value.
ContentView().globalValue.intValue=25
It is not changing the value. How can I change that observed object value? thanks...
Upvotes: 2
Views: 1454
Reputation: 9665
It is changing the value. The problem is you are instantiating an instance of GlobalValue locally in your struct. It has no life outside of the struct. I you want to use an Observable Object
as a global store like that, you need to create it once and use that instance.
The easiest way to do this is to add
static let shared = GlobalValue()
in your class, and in your struct use globalValue = GlobalValue.shared
which essentially gives you a singleton. You will have one instance that all the views can read and write to.
Upvotes: 2