1

- (void)windowControllerDidLoadNib:(NSWindowController *)aController用来查看文档何时加载到基于文档的应用程序中。但是我应该使用什么方法来查看文档何时关闭?我想将文本框的内容保存到 NSUserDefaults 但我找不到在文档关闭时调用的方法。我搜索了网络,并通过在 xcode 中显示为提示但没有运气的方法!任何帮助表示赞赏!

谢谢

4

1 回答 1

4

我观察NSApplicationWillTerminateNotification并重写了[NSDocument close]执行文档清理的方法([NSDocument close]应用程序终止时不调用!)

我的文档.h:

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

@end

我的文档.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];
}
于 2013-02-14T12:42:15.453 回答