I have a situation in SwiftData / CloudKit where I’m deleting a model object ParentA that has the following property:
@Relationship(deleteRule: .cascade, inverse: \Child.parentA) var children: [Child]?
After ParentA gets deleted, so will its children property and all the Child objects within. However, Child is also owned by a different model object ParentB, such that after ParentA gets deleted, I need to check and see if any ParentBs exist that have an empty Child array and delete them if so.
The problem is the SwiftData model doesn’t update immediately after I delete parentA, so that if I try to check which parentB.children are empty, the change will not have occurred (even with autosave turned on):
static func removeEmptyParentBs(in parentA: ParentA, from queriedChildren: [Child], modelContext: ModelContext)
{
if let children = parentA.children
{
for child in children.filter({ queriedChildren.contains($0) })
{
if let parentBChildren = child.parentB?.children
{
if (parentBChildren.isEmpty)
{
//delete parentB
}
}
}
}
}
To get the change to register, I have to put try? modelContext.save() or modelContext.processPendingChanges() at the top of removeEmptyParentBs. I’m wondering if there is a better way to go about syncing the results without having to force it to save or if not, which of those two is the best?