如果我在 NSDocument 中取消保存操作,则无法退出应用程序

Cannot quit the app if I cancel the save operation in a NSDocument

我正在子classing NSDocument class 以便在保存期间具有特定的行为。我将项目保存在一个文件夹中,并使用用于该项目的音频文件创建特定的子文件夹。

我覆盖了以下函数 save(to:ofType:for:delegate:didSave:contextInfo) 但我注意到一个奇怪的行为。假设我有以下实现:

override func save(to url: URL,
                   ofType typeName: String,
                   for saveOperation: NSDocument.SaveOperationType,
                   delegate: Any?,
                   didSave didSaveSelector: Selector?,
                   contextInfo: UnsafeMutableRawPointer?) {

    guard let customURL = createCustomUrlFrom(url: url) else { return }

    super.save(to: customURL,
               ofType: typeName,
               for: saveOperation,
               delegate: delegate,
               didSave: didSaveSelector,
               contextInfo: contextInfo)
}

我尝试创建自定义 URL,如果我无法做到,我会取消保存操作。

现在如果我在保存前退出应用程序,应用程序会提示我保存。如果我无法创建自定义 URL 并且我 return(在 super.save… 调用之前),则退出按钮或 "cmd+q" 不起作用!我必须强制退出才能关闭应用程序。

有人看到我在这里做错了什么吗?后台有什么东西 运行 阻止我关闭应用程序吗?

更新

可能是退出编辑文档时出现的sheet提示。我们有 window 说 Do you want to save the changes made to the document “Untitled”? 和 3 个按钮 Dont's savecancel save...

如果我点击保存,那么项目已经存在 我会显示一个 window 让用户替换项目或取消保存(它在 createTargetUrlFrom(url:) 函数中完成。如果用户选择取消应用无法退出。 所以我想到第一个 window 运行 在后台可能...

我找到了这个问题的解决方案!

事实上,应用程序正在等待 NSTerminateLater 的回复。我需要使用 reply(toApplicationShouldTerminate:) 函数。所以我只是在从 guard 语句返回之前添加了 NSApp.reply(toApplicationShouldTerminate: false)