3

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?

Judah Jacobson
  • 543
  • 4
  • 10
  • 1
    Interesting. This behaviour (receiving `-close` more than once) doesn’t seem to be documented. I think your suggestion of making `-close` safe to run multiple times is a good one. –  Apr 12 '11 at 05:00
  • In fact, you’re not the first to think of it: http://www.cocoabuilder.com/archive/cocoa/240166-nsdocument-close-method-calls-itself.html –  Apr 12 '11 at 05:12

1 Answers1

1

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.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75