如何告诉我的Cocoa应用程序从应用程序本身退出? [英] How can I tell my Cocoa application to quit from within the application itself?

查看:207
本文介绍了如何告诉我的Cocoa应用程序从应用程序本身退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个好的方法告诉我的Cocoa应用程序退出本身。请放心,这不会用于生产代码。我只是寻找一个简单的方法来运行一个测试,然后在调试期间关闭应用程序。

I'm looking for a good way to tell my Cocoa application to quit itself. Rest assured that this will not be used for production code. I'm just looking for an easy way to run one test and then close the application during debugging.

我发现 exit(0) ; 将关闭应用程序,但它绕过所有正常的应用程序退出过程,我想保留所有的应用程序。

I have found that exit(0); will close the app, but it bypasses all of the normal application exit procedures, and I would like to keep all of them in place.

基本上我想要的东西工作,好像一个用户从菜单中拔出退出,但我希望它能在我完成测试后自动进行。

Essentially I want things to work as if a user pulled "Quit" from the menu, but I want it to happen automatically after I have finished with my test.

我的代码目前看起来像这样:

My code currently looks like this:

#if (SUPERFANCY_TESTING_MODE)
    [self doSomething];
    exit(0); // <-- I need something better to go here
#endif


推荐答案

你可以放心,你的应用程序将被杀死至少一些时间。因此,防止退出 exit(0); 是必需的

You can pretty much rest assured that your app is going to get killed at least some of the time. Thus, defending against exits the like of exit(0); is required.

然而,NSApplication实现了 -terminate:方法。

However, NSApplication implements the -terminate: method.

[NSApp terminate:nil]; 应该做你想做的事。

我通常建议通过 -performSelector:afterDelay:发布,延迟为0.0,强制它发生在下一次通过的顶部事件循环。

I would generally suggest posting it via -performSelector:afterDelay: with a delay of 0.0 to force it to happen at the top of the next pass through the event loop.

示例:

[NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];

这篇关于如何告诉我的Cocoa应用程序从应用程序本身退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆