Hi CodeCrew,
Got a basic issue but I dont know how to solve it hence asking CodeCrew… Thanks
Use case is that I have a func in a model that I want to run in the background. This func needs to access data from another model… Can you help how to do this properly or why published variable of a model is not getting updated if I access it from another model?
To do this, I create an instance of the model() I need to access in another model.
Example below: TestModel2() needs access to TestModel()
class TestModel2 : ObservableObject {
init() {}
func printTestModel1() {
let testModel1 = TestModel()
print("testModel.testModel.element:\(testModel1.test.element)")
}
}
class TestModel : ObservableObject {
@Published var test: Test = Test()
init() {}
func printTestModel() {
print("testModel.testModel.element:\(self.test.element)")
}
func setElement(element: String) {
DispatchQueue.main.async {
self.test.element = element
}
}
}
Whilst I can access the function of TestModel() from TestModel2(), the published property in TestModel() is blank.
To test this, I have the view code below… if I tap on the button “TestModel1: printValue”, value is printed out. If I tap on the button “TestModel2: print element in TestModel1”, nothing is printed.
Here is the output from my console
testModel.testModel.element:123
testModel.testModel.element:
struct TestModelView: View {
@EnvironmentObject var testModel1: TestModel
@EnvironmentObject var testModel2: TestModel2
@State var stateElement: String = ""
var body: some View {
VStack (alignment: .leading) {
TextField("SomeValue", text: $stateElement)
Button {
testModel1.setElement(element: stateElement)
} label: {
Text("TestModel1: Set element")
}
Button {
testModel1.printTestModel()
} label: {
Text("TestModel1: printValue")
}
Button {
testModel2.printTestModel1()
} label: {
Text("TestModel2: print element in TestModel1")
}
}
.padding(10)
}
}