I'd really appreciate any concrete tip on how I should save the document, because everything I've tried doesn't work. Simply calling updateChangeCount(_:), like we already saw, messes with the undo mechanism. How is the text view able to save everything I input when the window first appears and then quit the app, but isn't able to when switching to another app and back again?
This is the last thing I tried, and when quitting the app the .terminateNow branch is always executed. Just calling endUndoGrouping() without beginUndoGrouping() logs an error in the Xcode console that no undo group is currently open.
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
for document in documents {
document.undoManager?.beginUndoGrouping()
document.undoManager?.endUndoGrouping()
}
let edited = documents.filter({ $0.hasUnautosavedChanges })
if edited.isEmpty {
return .terminateNow
}
var remaining = edited.count
for document in edited {
document.autosave(withImplicitCancellability: false) { [self] error in
if let error = error {
presentError(error)
} else {
remaining -= 1
if remaining == 0 {
NSApp.reply(toApplicationShouldTerminate: true)
}
}
}
}
return .terminateLater
}
Topic:
UI Frameworks
SubTopic:
AppKit
Tags: