Reputation: 31
I have trouble understanding why certain changes in my data do not propagate to my SwiftUI View.
This is a very minimal set-up to illustrate the issue:
public class Model: ObservableObject
{
@Published var anArray: [String]
// Calling this does NOT update the View
func addItem(item: String) {
anArray.append(item)
}
}
public class ViewModel: ObservableObject
{
@Published var model: Model
// Calling this updates the View
func addItem(item: String) {
model.addItem(item)
}
func getItem(index: Int) {
return model.anArray[index]
}
}
struct aView: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
VStack {
Text(viewModel.getItem(index: 0))
}
}
}
So when I use the addItem()
function on the ViewModel
, my View
gets updated. But in any situation where anArray
in the same instance of the model
class gets updated outside of the ViewModel
, the View
does not update. I would expect that the model
property would also publish changes to the referenced object when they happen from outside the ViewModel
. But obviously I misunderstand something.
How do I achieve updating the View
based on model
updates that happen through modifications outside of ViewModel
's context?
Upvotes: 0
Views: 21