I'm building a simple App using SwiftData. In my app a user can create, remove and edit posts. When editing, I want them to be able to hit "Save" to persist the changes or "Cancel" to discard the changes. The approach I'm using is to disable autosave and call modelContext.save()
when saving and modelContext.rollback()
when discarding the changes. So my modelContainer is defined as follows:
WindowGroup {
ContentView()
.modelContainer(for: [Post.self], isAutosaveEnabled: false)
}
and I Save and Cancel like this:
PostForm(post: post)
.toolbar {
ToolbarItemGroup(placement: .cancellationAction) {
Button("Cancel") {
if modelContext.hasChanges {
modelContext.rollback()
}
dismiss()
}
}
ToolbarItemGroup(placement: .confirmationAction) {
Button("Save") {
do {
if modelContext.hasChanges {
try modelContext.save()
}
} catch {
fatalError("Failed to save post: \(error.localizedDescription)")
}
callback?()
dismiss()
}
}
}
The issue I am facing is that after calling modelContext.rollback()
my Posts aren't updating in the UI, they still show the changes. Restarting the app shows the Posts without the changes so I'm guessing that modelContext.rollback()
is in fact discarding the changes and not persisting them in the Storage, the UI is the one that is not reacting to the change. Am I doing something wrong here? Is this approach correct?