How can I tell my Cocoa application to quit from within the application itself?

耗尽温柔 提交于 2019-12-03 04:13:55

问题


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.

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

回答1:


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.

However, NSApplication implements the -terminate: method.

[NSApp terminate: nil]; ought to do what you want.

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.

Example:

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


来源:https://stackoverflow.com/questions/1659177/how-can-i-tell-my-cocoa-application-to-quit-from-within-the-application-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!