0

I develop a document-based Cocoa application allowed saving documents asynchronous. Namely, my NSDocument subclass returns ture on canAsynchronouslyWrite(to:typeOf:for:).

I want dynamically and silently delay (or cancel) regular auto-saving if the document content is editing. At first, I thought it's enough when I throw an error in checkAutosavingSafety(), but it displays an error message dialog for user.

I believe there is a standard way for such a standard demand. But I'm not sure either where in a NSDocument subclass I should prevent saving and to which method I should say "please wait".

Does someone have any idea for this?

For the reference, the content of document is text which is managed by NSTextView subclass.

1024jp
  • 2,058
  • 1
  • 16
  • 25

1 Answers1

0

I finally found that throwing an .userCalcelled error in a saving process with autosavingIsImplicitlyCancellable can cancel autosaving.

/// make autosaving cancellable
override var autosavingIsImplicitlyCancellable: Bool {

    return true
}


/// save or autosave the document contents
override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, completionHandler: @escaping (Error?) -> Void) {

    // cancel if something is working
    guard saveOperation != .autosaveInPlaceOperation || !self.isEditing else {
        completionHandler(CocoaError(.userCancelled))
        return
    }

    super.save(to: newUrl, ofType: typeName, for: saveOperation, completionHandler: completionHandler)
}


/// whether your document is currently being edited
var isEditing: Bool {

    // check your document state
}
1024jp
  • 2,058
  • 1
  • 16
  • 25