且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NSWindow关闭时退出应用程序

更新时间:2022-04-28 03:30:59

您不能拥有windowDidClose事件,因为伴随它的通知将持有一个无效的对象(该窗口很可能在关闭时被释放了).要实现所需的功能,请让您的类成为Application的委托,并实现以下方法:

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). To achieve what you need, make your class the delegate of the Application, and implement the following method:

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

从该方法返回YES.

如果您的控制器对象在MainMenu.nib中具有实例,则只需从文件的所有者(这意味着MainMenu.nob文件中的应用程序对象)建立连接即可.按住Control键从File的Owner拖动到您的对象,然后连接代理出口.

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). Control-Drag from File's Owner to your object, and connect the delegate outlet.

或在源代码中,将类似以下内容的内容放入控制器对象的init方法中:

Or in source code, put something like this in your controller object's init method:

[NSApp setDelegate: self];