NSDocument 子类“close”方法被调用两次

发布于 2024-10-31 19:17:22 字数 834 浏览 0 评论 0原文

我有一个基于文档的 Cocoa 应用程序,它将 NSDocument 子类为 MyDocument。每个MyDocument 管理一个单独的后台进程(作为NSTask)。我想确保 NSTask 在其相应的 MyDocument 关闭或整个应用程序退出时终止。

对于后者,我让文档观察 NSApplicationWillTerminateNotification。 对于前者,我重写 close 方法:(

-(void)close {
    // Cleanup code here
    [super close];
}

顺便说一句,我不能将清理代码放在 dealloc 方法,因为该项目是 GC 的。)

问题是这样的:如果我打开一个 MyDocument,进行未保存的更改,然后按 cmd-Q,close 方法被调用两次。从调试器来看,调用链是: [MyDocument close] 调用 [NSDocument close],后者又调用 [NSWindowController _windowDidClose],后者又调用 [MyDocument close] > 再次。 (调用之后,应用程序退出)。

这是预期的行为吗?如果是这样,是否有更好的方法来释放文档特定的资源?或者我应该让 close 安全地运行多次?

I have a document-based Cocoa application which subclasses NSDocument as MyDocument. Each MyDocument manages a separate background process (as an NSTask). I want to make sure that the NSTask is terminated when its corresponding MyDocument closes or when the whole application quits.

For the latter, I make the document observe NSApplicationWillTerminateNotification. For the former, I override the close method:

-(void)close {
    // Cleanup code here
    [super close];
}

(Incidentally, I can't put cleanup code in the dealloc method since the project is GC'd.)

The problem is this: If I open a MyDocument, make unsaved changes and then press cmd-Q, the close method is called twice. From the debugger, the call chain is:
[MyDocument close] calls [NSDocument close], which calls [NSWindowController _windowDidClose], which calls [MyDocument close] again. (After that call, the application quits).

Is this expected behavior? If so, is there a better way to release document-specific resources? Or should I just make close safe to run multiple times?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流绪微梦 2024-11-07 19:17:22

我相信我在 cocoadev 邮件列表上看到过一篇帖子,说这是目前框架的正常行为(但将来可能会改变)。您应该使您的 -close 方法足够强大以处理多个调用,因为 AppKit 不保证它只会被调用一次。

我不认为您需要关心 NSApplicationWillTerminateNotification,因为如果我理解正确的话,当您的应用程序也终止时,任务将自动终止。此外,如果您支持突然终止,您的应用程序可能会在没有通知的情况下被终止。

I believe I've seen a post to the cocoadev mailing list saying that this is normal behaviour for the frameworks at the moment (but that it might change in future). You should make your -close method robust enough to handle multiple calls since no guarantee is made by AppKit that it will be called only once.

I don't believe you need care about NSApplicationWillTerminateNotification, since if I understand correctly, tasks will automatically be terminated when your app is too. Furthermore, if you support sudden termination, your app can be killed without notice/notification anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文