关闭窗口时释放NSWindowController

问题描述 投票:5回答:2

我正在构建一个Cocoa应用程序,并且对使用窗口控制器有疑问。这个想法是,如果用户从菜单栏中选择“新建”,则将创建作为NSWindowController子类的MyWindowController实例,并显示MyWindow.xib中的新窗口。

我正在处理应用程序委托中的操作。从经过类似以下搜索之后我所看到的结果可以完成。一旦显示了窗口,我就没有理由再存储指向窗口控制器的指针了,因为我已经分配了指针,所以在显示窗口之前我也会自动释放它。

[[[[MyWindowController alloc] init] autorelease] showWindow:self];

由于此后不久便释放了该窗口,因此该窗口将短暂显示在屏幕上,然后消失。我找到了一种解决方案,其中将窗口控制器保留在-showWindow:方法中,并使其在收到windowWillClose通知后立即释放。

- (IBAction)showWindow:(id)sender
{
    [self retain];
    [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowWillCloseNotification
                                                      object:self.window
                                                       queue:nil
                                                  usingBlock:^(NSNotification *note) {
                                                      [self release];
                                                  }];
    [super showWindow:sender];
}

有更好的方法吗?我已经搜索了Apple文档,但没有找到任何可以使用的实践方法。听起来应该很基础,所以也许我只是在搜索错误的术语。

objective-c cocoa memory-management nswindow nswindowcontroller
2个回答
5
投票

通常,您将坚持使用窗口控制器,并仅在完成后才释放它。我想说您的应用程序代表将对此负责。如果可以有多个,只需将它们存储在一个数组中。尽管您的解决方案可能有效,但它不是很好。

如果您正在使用基于文档的Cocoa应用程序,请在文档子类方法makeWindowControllers中创建窗口控制器,并让该类持有指向您的窗口控制器的指针。


0
投票
func windowShouldClose(_ sender: NSWindow) -> Bool {

    #if DEBUG
    let closingCtl = sender.contentViewController!
    let closingCtlClass = closingCtl.className
    print("\(closingCtlClass) is closing")
    #endif


    sender.contentViewController = nil // will force deinit.

    return true // allow to close.
}
© www.soinside.com 2019 - 2024. All rights reserved.