Changing the data in a SwiftUI OutlineGroup

623 views Asked by At

I'm trying to use the new SwiftUI OutlineGroup to display an expandable tree. I tried this in my app's ContentView:

struct ContentView: View {

    @EnvironmentObject var store: MyDataStore

    var body: some View {
        List { 
            OutlineGroup(store.navRoot, children: \.children) { item in
                Text(item.name)
            }
        }
    }

The code for the store and the command handler that tries to change the tree data:

// Clicking menu button calls this
private func newProject() {
    var new = LeftNavNode(id: UUID(), name: "Foo")
    store.navRoot.children!.append(new)        
}   

...

class MyDataStore: ObservableObject {
    @Published var navRoot = LeftNavNode(id: projectsID, name: "Projects",
                                         children: [
                                            LeftNavNode(id: UUID(), name: "Project1"),
                                            LeftNavNode(id: UUID(), name: "Project2")
                                            ])
}

struct LeftNavNode: Identifiable {
    let id: UUID
    let name: String
    var children: [LeftNavNode]? = nil
}

It works to display static data, but when I add an item to the tree, I get an error. The state changes, the view re-renders, and I get this:

2020-09-20 15:08:24.991604-0400 MyArchives[32728:584579] [General] NSOutlineView error inserting child indexes <_NSCachedIndexSet: 0x600000760ea0>[number of indexes: 1 (in 1 ranges), indexes: (3)] in parent 0x0 (which has 1 children).

How do you change the tree model without crashing?

0

There are 0 answers