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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With