Whenever a user returns to a form sub-view after saving data through a binding variable, the form displays old data from before it was edited, and I cannot understand why.
I have an array of Face objects (technically Core Data entities) declared as a State variable in a parent NavigationView. I then loop through them to create NavigationLinks like this:
@State var formDieFaces: [Face] = [] // this gets initialized akin to the below (truncated)
...
let face1 = Face(entity: Face.entity(), insertInto: nil)
self._formDieFaces = State(initialValue: [face1])
...
ForEach (formDieFaces.indices) { curIndex in
NavigationLink(
destination: FaceForm(self.$formDieFaces[curIndex]))
) {
FaceRowView(faceToList: self.formDieFaces[curIndex])
}
}
(Yes, I am intentionally initializing this array of Face objects by inserting into a nil
moc for temporary purposes while the user edits everything. I then iterate through that array and create new Face objects in the actual moc during the save process.)
And in FaceForm, I receive the variable and "save" it as such:
@Binding var faceToEdit: Face
@State var formFaceText: String = String()
...
// in the form
TextField("Placeholder text", text: $formFaceText)
...
// on save, do the below
self.faceToEdit.text = self.formFaceText
What's weird is that on "saving" in FaceForm, the main NavigationView does update, and in that NavigationLink (FaceRowView) everything shows the correct data. But if I click back into FaceForm thereafter, it displays old data from before the save.
I have a feeling I'm doing something phenomenally obtuse with the State and Binding variables, but I just can't for the life of me figure out what's going on. I've tried various combinations of @ObservedObject, @ObservableObject, @StateObject, etc.
Could anyone please point me in the right direction?
(To be clear, FaceRowView works and displays the correct data. FaceForm is where the problem is occurring, almost like it's remembering an old copy of the data.)
If it's helpful, here is a link to a video of the behavior: https://youtu.be/8eC-TdtFP5s
---
EDIT: for those wondering, I'm not 100% sure this is a pure, proper SwiftUI solution, but I found a hack/workaround on this page that I've implemented and seems to have "solved" the problem: https://stackoverflow.com/a/57733708.