I’m trying to take advantage of SwiftData’s automatic undo/redo support in a SwiftUI macOS app. I’ve overcome one of the wrinkles of getting it to work with relationships, but am stuck on another and wondering if I’m missing something or if it’s in fact a SwiftData bug.
I essentially have a one-to-many relationship between parent and child entities. Undoing and redoing insertion or deletion of parent entities works fine. Undoing insertion of child entities also works fine (this required adding the object to the model context before setting the parent relationship). But redoing insertion or undoing deletion of child entities doesn’t work. The child simply won’t reappear.
Here’s a simple test app to reproduce the problem:
import SwiftUI
import SwiftData
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Parent.self, isUndoEnabled: true)
}
}
@Model
final class Parent {
@Attribute(.unique) var timestamp = Date.now
@Relationship(deleteRule: .cascade, inverse: Child.parent)
var children = [Child]()
init() {}
}
@Model
final class Child {
@Attribute(.unique) var timestamp = Date.now
var parent: Parent?
init() {}
}
struct ContentView: View {
@Environment(.modelContext) private var modelContext
@Query private var parents: [Parent]
var body: some View {
List {
ForEach(parents.sorted(by: { $0.timestamp < $1.timestamp })) { parent in
HStack {
Text("Parent (parent.timestamp.description)")
Button("Add Child") {
let child = Child()
modelContext.insert(child)
child.parent = parent
}
Button("Delete") {
modelContext.delete(parent)
}
}
ForEach(parent.children.sorted(by: { $0.timestamp < $1.timestamp })) { child in
HStack {
Text("Child (child.timestamp.description)")
Button("Delete") {
modelContext.delete(child)
}
}
}
.padding([.leading], 20)
}
}
.toolbar {
Button("Add Parent") {
modelContext.insert(Parent())
}
}
}
}
Removing the delete rule doesn’t make a difference. Setting the parent
property to nil before deletion also doesn’t help.
Am I doing something wrong or should report this as a bug to Apple?