Where do you put cleanup code for NSDocument sub-classes?

雨燕双飞 提交于 2019-11-30 20:07:25

Have each document add itself as an observer in the local notification center for NSApplicationWillTerminateNotification. In its notification method, call its clean-up method (which you should also call from dealloc or close).

Obliquely

The correct answer here didn't fit my use case, but the question does. Hence the extra answer.

My use case: closing a document (which may be one of several that are open) but not closing the application.

In this case (at time of writing and unless I'm just looking in the wrong place) the documentation is not as helpful as it could be.

I added a canCloseDocumentWithDelegate:shouldCloseSelector:contextInfo: override in my NSDocument subclass and called super within it. The documentation doesn't say whether you must call super, but a bit of logging shows that the system is providing a selector and a context. This method is called just before the document is closed.

- (void) canCloseDocumentWithDelegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo;
{
    if ([self pdfController])
    {
        [[[self pdfController] window] close];
        [self setPdfController: nil];
    }

    [super canCloseDocumentWithDelegate:delegate shouldCloseSelector: shouldCloseSelector contextInfo: contextInfo];    
}

There is some useful discussion of this method on CocoaBuilder. If there's downsides to this approach or better ways of doing this, please comment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!