call exit(0) in iphone app

From Apple’s Human User Guidelines…

Don’t Quit Programmatically

Never quit an iOS application programmatically because people tend to
interpret this as a crash. However, if external circumstances prevent
your application from functioning as intended, you need to tell your
users about the situation and explain what they can do about it.
Depending on how severe the application malfunction is, you have two
choices.

Display an attractive screen that describes the problem and suggests a
correction. A screen provides feedback that reassures users that
there’s nothing wrong with your application. It puts users in control,
letting them decide whether they want to take corrective action and
continue using your application or press the Home button and open a
different application

If only some of your application’s features are not working, display
either a screen or an alert when people activate the feature. Display
the alert only when people try to access the feature that isn’t
functioning.

If you’ve decided that you are going to quit programmatically anyway…

In C, exit(0) will halt execution of the application. This means that no delegate methods or exception handlers will be called. So, if the goal is to make sure that some code gets called when the closes, even on a forced close, there may be another option. In your AppDelegate implement a custom method called something like -(void)applicaitonIsgoingAway. Call this method from within anywhere you want your exiting code to be called:

  1. applicationWillTerminate
  2. applicationDidEnterBackground
  3. onUncaughtException

The first two are ones that you already mentioned in your question. The third can be a catch-all of sorts. It’s a global exception handler. This next bit comes from a question on that very topic.

This exception handler will get called for any unhanded exceptions (which would otherwise crash your app). From within this handler, you can call applicaitonIsgoingAway, just like in the other 2 cases. From the other question that I mentioned above, you can find an answer similar to this.

void onUncaughtException(NSException* exception)
{
    [[AppDelegate sharedInstance] applicationIsgoingAway];
}

But in order for this to work, you need to set this method up as the exception handler like so…

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSSetUncaughtExceptionHandler(&onUncaughtException);
 //There may already be more code in this method.
}

Now, you can quit the app programmatically by calling NSAssert(FALSE, @"Quitting the app programmatically."); As long as there is no other exception handler in place to catch this, your app will begin to crash, and your exception handler code will be called. in-turn calling applicationIsGoingAway.

Leave a Comment