Thanks. I added a link to this post to the feedback.
NSDocument.fileURL is nil for a new document that hasn't been saved – In that case, when you try to terminate your app or close the document window, AppKit shows an alert asking if you'd save the document, and so you should be fine.
Yes, but only assuming that the document has been marked as dirty... which is what we're trying to work around.
I noticed that there is another issue now:
Create a new document.
Type a letter.
Switch to another app and back again.
Type another letter.
Quit and restart the app.
The document is correctly restored, but when selecting File > Close (or hitting Command-W), it is closed without asking whether I want to save or discard it, and so it probably stays in its autosave directory without the user knowing where it is.
This is my current implementation:
class Document: NSDocument {
private var textStorage: NSTextStorage!
private(set) var savedText: String?
override func data(ofType typeName: String) throws -> Data {
savedText = textStorage.string
...
}
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
var remaining = 1
for document in documents as! [Document] {
if document.textStorage.string != document.savedText, let fileURL = document.fileURL, let fileType = document.fileType {
remaining += 1
document.save(to: fileURL, ofType: fileType, for: .saveOperation) { [self] error in
if let error = error {
presentError(error)
} else {
remaining -= 1
if remaining == 0 {
NSApp.reply(toApplicationShouldTerminate: true)
}
}
}
}
}
remaining -= 1
return remaining == 0 ? .terminateNow : .terminateLater
}
Topic:
UI Frameworks
SubTopic:
AppKit
Tags: