Search code examples
objective-ccocoamethodsnsdocument

method called in document.m on closing of document


i use - (void)windowControllerDidLoadNib:(NSWindowController *)aController to see when a document has been loaded in a document based application. But what method should I use to see when a document is beeing closed? i would like to save the content of a textbox to the NSUserDefaults but i am unable to find a method that is called whenever the document is closing. i searched the web and also trough the methods that appear as hint in xcode but without luck! any help appreciated!

thanks


Solution

  • I observe NSApplicationWillTerminateNotification and override the [NSDocument close] method to perform document clean-up ([NSDocument close] isn't called when the app terminates!)

    MyDocument.h:

    @interface MyDocument : NSDocument
    {
        BOOL _cleanedUp;    // BOOL to avoid over-cleaning up
        ...
    }
    
    @end
    

    MyDocument.m:

    // Private Methods
    @implementation MyDocument ()
    
    - (void)_cleanup;
    
    @end
    
    @implementation MyDocument
    
    - (id)init
    {
        self = [super init];
        if (self != nil)
        {
            _cleanedUp = NO;
    
            // Observe NSApplication close notification
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(_cleanup)
                                                         name:NSApplicationWillTerminateNotification
                                                       object:nil];
        }
        return self;
    }
    
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    
        // I'm using ARC so there is nothing else to do here
    }
    
    - (void)_cleanup
    {
        if (!_cleanedUp)
        {
            _cleanedUp = YES;
            logdbg(@"Cleaning-up");
    
            // Do my clean-up
        }
    }
    
    - (void)close
    {
        logdbg(@"Closing");
    
        [self _cleanup];
    
        [super close];
    }