如何以编程方式退出mac应用程序?

时间:2022-08-26 00:02:27

I need to add a quit-button to my application that runs from the menubar in mac. How do I programmatically quit an application in mac?

我需要在mac上的menubar上添加一个quit-button,我如何以编程方式退出mac中的应用程序?

4 个解决方案

#1


74  

There is a simpler form to quit from code:

有一种更简单的形式可以退出代码:

[NSApp terminate:self];

But as you're adding a button, all you have to do is to control drag from your button to the Application icon and connect the method terminate:.

但是,在添加按钮时,所要做的就是控制从按钮拖拽到应用程序图标并连接方法terminate:。

如何以编程方式退出mac应用程序?如何以编程方式退出mac应用程序?

#2


20  

[[NSApplication sharedApplication] terminate:self];

#3


4  

Try the following:

试试以下:

[NSApp terminate: nil];

#4


1  

In some case you cannot close app when call [NSApp terminate:self];. Like when showing NSAlert as sheet on the doc window (NSAlert -beginSheetModalForWindow:completionHandler:) ...

在某些情况下,调用[NSApp terminate:self]时不能关闭app;就像当在doc窗口上显示NSAlert时一样(NSAlert -beginSheetModalForWindow:completionHandler:)……

You can close all window and alert before call terminate, like following code:

您可以关闭所有窗口和警报,在调用终止之前,像以下代码:

for (NSWindow *window in [NSApplication sharedApplication].windows) {
    [window close];
}
[NSApp terminate:self];

#1


74  

There is a simpler form to quit from code:

有一种更简单的形式可以退出代码:

[NSApp terminate:self];

But as you're adding a button, all you have to do is to control drag from your button to the Application icon and connect the method terminate:.

但是,在添加按钮时,所要做的就是控制从按钮拖拽到应用程序图标并连接方法terminate:。

如何以编程方式退出mac应用程序?如何以编程方式退出mac应用程序?

#2


20  

[[NSApplication sharedApplication] terminate:self];

#3


4  

Try the following:

试试以下:

[NSApp terminate: nil];

#4


1  

In some case you cannot close app when call [NSApp terminate:self];. Like when showing NSAlert as sheet on the doc window (NSAlert -beginSheetModalForWindow:completionHandler:) ...

在某些情况下,调用[NSApp terminate:self]时不能关闭app;就像当在doc窗口上显示NSAlert时一样(NSAlert -beginSheetModalForWindow:completionHandler:)……

You can close all window and alert before call terminate, like following code:

您可以关闭所有窗口和警报,在调用终止之前,像以下代码:

for (NSWindow *window in [NSApplication sharedApplication].windows) {
    [window close];
}
[NSApp terminate:self];