Reputation: 11
I'm trying to create a data structure in SwiftData that uses a many-to-one relationship, however, the parents list of children is not being appended to until the app is restarted.
I've modified the SwiftData example app to demonstrate the problem:
Creating a Parent and Child class with a many-to-one relationship:
@Model
final class Parent {
@Relationship(deleteRule: .cascade, inverse: \Child.parent)
var Children = [Child]()
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
@Model
final class Child {
var parent: Parent
init(parent: Parent) {
self.parent = parent
}
}
List view of all Parents, which each lead to a list of their children:
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var parents: [Parent]
var body: some View {
NavigationSplitView {
List {
ForEach(parents) { parent in
NavigationLink {
Text("Parent")
Button("Add Child") {
addChild(parent: parent)
}
List {
ForEach(parent.Children) { child in
Text("Child")
}
}
} label: {
Text(parent.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addParent) {
Label("Add Parent", systemImage: "plus")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addParent() {
withAnimation {
let newParent = Parent(timestamp: Date())
modelContext.insert(newParent)
addChild(parent: newParent)
}
}
private func addChild(parent: Parent) {
withAnimation {
let newChild = Child(parent: parent)
modelContext.insert(newChild)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(parents[index])
}
}
}
}
When the plus toolbar button is pressed a new parent is created along with a child. Following the navlink shows a list containing this one child. Attempting to add new children results in them being inserted but not appended to the parents list of children. Restarting the app and then clicking on the parent shows the list containing all the previously inserted children now properly appended.
Is anyone aware of what I'm doing wrong here?
Upvotes: 1
Views: 133