防止 NSDocument 在其内容编辑时自动保存 [英] Prevent NSDocument's auto-saving while its content is editing
问题描述
我开发了一个基于文档的 Cocoa 应用程序,允许异步保存文档.即,我的 NSDocument 子类在 canAsynchronouslyWrite(to:typeOf:for:)
上返回 ture.
I develop a document-based Cocoa application allowed saving documents asynchronous. Namely, my NSDocument subclass returns ture on canAsynchronouslyWrite(to:typeOf:for:)
.
如果文档内容正在编辑,我希望动态且静默地延迟(或取消)定期自动保存.起初,我认为在 checkAutosavingSafety()
中抛出错误就足够了,但它为用户显示了一个错误消息对话框.
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.
我相信对于这样的标准需求有标准的方法.但是我不确定我应该在 NSDocument 子类中的哪个位置阻止保存,以及我应该说请稍候".
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?
作为参考,文档的内容是由 NSTextView 子类管理的文本.
For the reference, the content of document is text which is managed by NSTextView subclass.
推荐答案
我终于发现在使用 autosavingIsImplicitlyCancellable
的保存过程中抛出 .userCalcelled
错误可以取消自动保存.
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
}
这篇关于防止 NSDocument 在其内容编辑时自动保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!