[英]Difference between ways to quit an application: exit(), NSApp/NSApplication terminate
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. 作为Objective-C的新手,所有这些对我来说都很合理。 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. NSApp
是一个保存应用程序对象的全局变量。 [NSApplication sharedApplication]
returns the application object or, if this is the first call, creates it and then returns it. [NSApplication sharedApplication]
返回应用程序对象,如果这是第一次调用,则创建它然后返回它。 If you're considering exiting the app, this is almost certainly not the first call. 如果你正在考虑退出应用程序,这几乎肯定不是第一次打电话。
The -terminate:
method ignores the argument ( sender
). -terminate:
方法忽略参数( 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. 请注意,
-terminate:
不会简单地退出应用程序。 It will call the app delegate's -applicationShouldTerminate:
method, if implemented. 它将调用app delegate的
-applicationShouldTerminate:
方法(如果已实现)。 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. 最后,如果应用程序(最终)终止,
NSApplication
将发布NSApplicationWillTerminateNotification
通知。 If the app delegate implements -applicationWillTerminate:
, that will be called as a result of posting that notification. 如果app委托实现了
-applicationWillTerminate:
,那么将通过发布该通知来调用它。 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(0)
提供任何机会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.