简体   繁体   English

NSWindow关闭时退出应用程序

[英]Quit app when NSWindow closes

How correctly to quit the Mac OS X app, when the main (the only one) closes? 当主(唯一)关闭时,如何正确退出Mac OS X应用程序?

I know there a method - (void)windowWillClose:(NSNotification *)notification in NSWindowDelegate . 我知道在NSWindowDelegate有一个方法- (void)windowWillClose:(NSNotification *)notification But it isn't quite suitable in my case, because it is called before NSWindow closes. 但它在我的情况下并不合适,因为它 NSWindow关闭之前被调用。

You cannot have windowDidClose event since the notification that accompanies it would be holding an invalid object (the window is likely to have been deallocated on close). 你不能拥有windowDidClose事件,因为伴随它的通知将持有一个无效的对象(该窗口很可能在关闭时被释放)。 To achieve what you need, make your class the delegate of the Application, and implement the following method: 要实现您的需要,请将您的类作为Application的委托,并实现以下方法:

- (BOOL) applicationShouldTerminateAfterLastWindowClosed: (NSApplication *) theApplication;

From that method, return YES . 从该方法,返回YES

If your controller object has an instance in the MainMenu.nib , just make a connection from File's Owner (which means Application Object in the MainMenu.nob file). 如果您的控制器对象在MainMenu.nib有一个实例,只需从File的Owner(这意味着MainMenu.nob文件中的Application Object)建立连接。 Control-Drag from File's Owner to your object, and connect the delegate outlet. 控制 - 从文件所有者拖动到您的对象,并连接代理插座。

Or in source code, put something like this in your controller object's init method: 或者在源代码中,在控制器对象的init方法中输入这样的内容:

[NSApp setDelegate: self];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM