退出应用程序的方式之间的区别:exit(),NSApp / NSApplication terminate [英] Difference between ways to quit an application: exit(), NSApp/NSApplication terminate
问题描述
我查找了如何在线退出应用程序,我发现了很多冲突的答案。不同的人提出以下建议,每个都有不同的原因:
[NSApp terminate:self];
[NSApp terminate:nil];
[[NSApplication sharedApplication] terminate:self];
作为对Objective-C的新手,他们对我来说看起来都很合理。
$ p$ b
[NSApp terminate:self];
[NSApp terminate:nil];
[[NSApplication sharedApplication] terminate:self];
做同样的事情。 NSApp
是一个保存应用程序对象的全局变量。 [NSApplication sharedApplication]
返回应用程序对象,如果这是第一个调用,则创建它,然后返回它。
-terminate:
如果你正在考虑退出应用程序,方法忽略参数( sender
)。
注意 -terminate:
-applicationShouldTerminate:
方法(如果实现)。根据返回代码,代理可以取消终止或推迟决定。 最后,如果应用程序(最终)终止,如果决定被延迟,应用程序将以特殊模式运行等待它。 NSApplication
将会发布 NSApplicationWillTerminateNotification
通知。如果应用程序委托实现 -applicationWillTerminate:
,则将由于发布该通知而被调用。代理可以做一些最后的清理。
调用退出(0)
I looked up how to quit an application online, and I've found a lot of conflicting answers. Different people have suggested the following, each with different reasons:
exit(0);
[NSApp terminate:self];
[NSApp terminate:nil];
[[NSApplication sharedApplication] terminate:self];
Being new to Objective-C, all of them seem pretty reasonable to me. When is each method most appropriate to use?
All of these:
[NSApp terminate:self];
[NSApp terminate:nil];
[[NSApplication sharedApplication] terminate:self];
do the same thing. NSApp
is a global variable which holds the application object. [NSApplication sharedApplication]
returns the application object or, if this is the first call, creates it and then returns it. If you're considering exiting the app, this is almost certainly not the first call.
The -terminate:
method ignores the argument (sender
). The only reason it takes an argument is that it's an action method and that's the general form of action methods.
Note that -terminate:
will not simply exit the app. It will call the app delegate's -applicationShouldTerminate:
method, if implemented. Depending on the return code, the delegate can cancel termination or defer the decision. If the decision is deferred, the application will run in a special mode waiting for it.
Finally, if the app does (eventually) terminate, NSApplication
will post the NSApplicationWillTerminateNotification
notification. If the app delegate implements -applicationWillTerminate:
, that will be called as a result of posting that notification. The delegate can do some final cleanup. In addition to the delegate, there can be arbitrary other observers of that notification that want a chance to do cleanup.
Calling exit(0)
provides no opportunity for any of this.
这篇关于退出应用程序的方式之间的区别:exit(),NSApp / NSApplication terminate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!