Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. When is each method most appropriate to use?

like image 414
user3932000 Avatar asked Aug 12 '14 07:08

user3932000


1 Answers

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.

like image 108
Ken Thomases Avatar answered Oct 08 '22 04:10

Ken Thomases