当窗口关闭时释放一个 NSWindowController
我正在构建一个 Cocoa 应用程序,并且有一个关于使用窗口控制器的问题。这个想法是,如果用户从菜单栏中选择“New”,则会创建一个 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 文档,但没有找到任何有关使用哪些做法的信息。这听起来像是它应该涵盖的非常基本的内容,所以也许我只是用错误的术语进行搜索。
I'm building a Cocoa application and have a question about using window controllers. The idea is that if the user selects New from the menu bar, an instance of MyWindowController which is a subclass of NSWindowController is created and a new window from MyWindow.xib is displayed.
I'm handling the action in the application delegate. From what I have seen after searching around something like the following could be done. Once the window is displayed I don't have any reason to store a pointer to the window controller anymore and since I allocated it I also autorelease it before displaying the window.
[[[[MyWindowController alloc] init] autorelease] showWindow:self];
Since the window is released soon afterwards the window will briefly display on the screen and then go away. I have found a solution where I retain the window controller in the -showWindow: method and let it release itself once it gets a windowWillClose notification.
- (IBAction)showWindow:(id)sender
{
[self retain];
[[NSNotificationCenter defaultCenter] addObserverForName:NSWindowWillCloseNotification
object:self.window
queue:nil
usingBlock:^(NSNotification *note) {
[self release];
}];
[super showWindow:sender];
}
Is there a better way to do this? I have searched the Apple documentation and have not found anything on which practices to use. It sounds like something very basic which it should cover so maybe I'm just searching with the wrong terms.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您会握住窗口控制器,只有在使用完毕后才释放它。我想说你的应用程序代表将对此负责。如果可以有多个,只需将它们存储在一个数组中。虽然您的解决方案可能有效,但它不是很优雅。
如果您正在开发基于文档的 Cocoa 应用程序,则可以在文档子类方法 makeWindowControllers 中创建窗口控制器,并让该类保存指向窗口控制器的指针。
Normally you would hold on to the window controller, and only release it when you are done with it. I'd say that your app delegate would be responsible for that. Just store them in an array if there can be multiple. Whilst your solution may work, it's not very elegant.
If you are working on a document based Cocoa app, you create the window controller in your document subclass method makeWindowControllers and let that class hold a pointer to your window controller.