Snap button action to close application in Cocoa

I created a window with an exit button. In my .h controller, I created such an action.

-(IBAction) exitApp : (NSButton*) sender; 

What should be written in the corresponding .m controller, so that the application terminates when I click the "Exit" button.

+4
source share
3 answers

If your only goal is to close the application, you do not need a special action for this. Just attach your button to the terminate: action in the Application object in Interface Builder.

If you need this regular exitApp: action, you can define it as follows:

 - (IBAction)exitApp:(NSButton*)sender { // custom termination code [[NSApplication sharedApplication] terminate:nil]; } 
+9
source

You do not even need to write an action method for this purpose. The "file owner" of the main nib is an instance of NSApplication that represents the running application, and it has a terminate: method that terminates the application.

So, just connect your button to the terminate: method terminate: "File Owner". You can see that the "Exit" entry in the menu bar provided by the interface builder is connected to the same method of the same target.

If you really insist, do

 -(IBAction)exitApp:(NSButton*)sender { [[NSApplication sharedApplication] terminate:nil]; } 

Finally, note that the application is not made to exit , but the application is made in quit . So, on your button, do not put the Exit shortcut ... it's Windows-rev. Use the verb Exit instead. The terminate verb in the method selector is NextStep-ism, remaining in Cocoa terminology, but you should not use it in the visible parts of your application.

Another thing is that you can implement the delegate method

 -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication { return YES; } 

so that the application closes automatically when the last window is closed, and then you can end the quit button. See the documentation .

+11
source
 -(IBAction) exitApp:(id)sender { [NSApp terminate: nil]; } 
+4
source

Source: https://habr.com/ru/post/1340929/


All Articles