0

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!

Cameron Delong
  • 454
  • 1
  • 6
  • 12

2 Answers2

0

try using this in "InstanceView":

@State var instance: Instance

or

@Binding var instance: Instance

If that does not work your best bet is to make "Instance" a class and ObservableObject and do it that way.

  • State and Binding didn't work unfortunately. I'd like to try to use ObservableObject but I'm not sure how I do that with a class from Coredata. This is my Instance Class: https://pastebin.com/20hTjMFy. I think NSManagedObject already conforms to ObservableObject? But I'm not sure where to go from there. – Cameron Delong Jul 01 '21 at 01:04
0

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.

Cameron Delong
  • 454
  • 1
  • 6
  • 12