Reputation: 543
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?
Upvotes: 3
Views: 681
Reputation: 15003
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.
Upvotes: 1