Search code examples
swiftcore-dataswiftuiswiftui-navigationview

SwiftUI - View not updating after adding linked object in Coredata


I have a SwiftUI view called InstanceView, which shows the details of an Instance from a NagivationView. The links in the NavigationView are objects from Coredata called Instances, and also in Coredata, I have an entity called Solve. Instance has a one-to-many relationship with Solve. InstanceView displays a list of the Solves linked to it.

My problem is that when I create a new Solve, and add it to an Instance, from my InstanceView, the new solve doesn't appear in the InstanceView until I select a different Instance in the NavigationView, and return to the original Instance.

Here is the List inside the NavigationView that controls which Instance is shown in the InstanceView:

List {
    ForEach(Array(zip(instances.indices, instances)), id: \.0) { index, instance in
        NavigationLink(destination: InstanceView(instance: instance), tag: index, selection: $selectedInstanceIndex) {
            InstanceRow(instance: instance)
        }
    }
}

This is the InstanceView:

struct InstanceView: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    var instance: Instance
    
    var body: some View {
        List {
            ForEach(instance.solveArray, id: \.self) { solve in
                Text(String(solve.time))
            }
        }
        .navigationTitle(instance.wrappedName)
        .navigationSubtitle(instance.wrappedPuzzle)
        
        Button("add solve") {
            addSolve()
        }
        
    }
    
    private func addSolve() {
        withAnimation {
            let newSolve = Solve(context: viewContext)
            newSolve.time = 3.2
            newSolve.dnf = false
            newSolve.plusTwo = false
            newSolve.timestamp = Date()

            instance.addToSolve(newSolve)

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

So I was wondering how I could force the InstanceView to update so that it shows the new Solve added from inside it.

Thanks!


Solution

  • I figured this out and figured I would post my solution in case anyone else had the same problem. I was able to solve this just by adding @ObservedObject in front of var instance: Instance.