Monday, July 22, 2024
HomeiOS Developmentios - SwiftData rollback not updating the UI

ios – SwiftData rollback not updating the UI


I am constructing a easy App utilizing SwiftData. In my app a consumer can create, take away and edit posts. When enhancing, I need them to have the ability to hit “Save” to persist the adjustments or “Cancel” to discard the adjustments. The strategy I am utilizing is to disable autosave and name modelContext.save() when saving and modelContext.rollback() when discarding the adjustments. So my modelContainer is outlined as follows:

WindowGroup {
     ContentView()
         .modelContainer(for: [Post.self], isAutosaveEnabled: false)
}

and I Save and Cancel like this:

PostForm(publish: publish)
    .toolbar {
        ToolbarItemGroup(placement: .cancellationAction) {
            Button("Cancel") {
                if modelContext.hasChanges {
                    modelContext.rollback()
                }
                
                dismiss()
            }
        }
        
        ToolbarItemGroup(placement: .confirmationAction) {
            Button("Save") {
                do {
                    if modelContext.hasChanges {
                        strive modelContext.save()
                    }
                } catch {
                    fatalError("Failed to save lots of publish: (error.localizedDescription)")
                }
                
                callback?()
                dismiss()
            }
        }
    }

The difficulty I’m going through is that after calling modelContext.rollback() my Posts aren’t updating within the UI, they nonetheless present the adjustments. Restarting the app exhibits the Posts with out the adjustments so I am guessing that modelContext.rollback() is actually discarding the adjustments and never persisting them within the Storage, the UI is the one that’s not reacting to the change. Is that this strategy appropriate? How can I make it in order that the discarded adjustments from modelContext.rollback() are up to date within the UI?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments