开发者

Binding Button action to close an App in Cocoa

开发者 https://www.devze.com 2023-02-13 09:04 出处:网络
I have created a window with an exit button in place. In开发者_Python百科 my controller.h, I have created an action like this.

I have created a window with an exit button in place. In开发者_Python百科 my controller.h, I have created an action like this.

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

What should I write in the corresponding controller.m, so that the application terminates when I click the 'Exit' button.


If your only objective is to terminate the application, you don’t need a custom action for that. Simply hook your button to the terminate: action in your Application object in Interface Builder.

If you do need that custom exitApp: action, you can define it like this:

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


You don't even have to write an action method for this purpose. The "File's Owner" of the main nib is the NSApplication instance representing the running application itself, and it has a method terminate: which terminates the app.

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

If you really insists, implement

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

Finally, note that an application is not made to exit, but that an application is made to quit. So, on your button, don't put the label Exit... this is a Windows-ism. Instead, use the verb Quit. The verb terminate in the method selector is a NextStep-ism remaining in the Cocoa terminology, but you shouldn't use it in the visible parts of your app.

Another thing is that you can implement the delegate method

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

so that the app automatically quits when the last window is closed, and then you can do away with the quit button. See the documentation.


-(IBAction) exitApp:(id)sender {
  [NSApp terminate: nil];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消