tags:

views:

278

answers:

1

I have read questions/559482/why-doesnt-an-iphone-apps-main-function-ever-get-a-chance-to-finish, which explains why NSApplicationMain never actually returns. The same thing happens (for the same reason) in a desktop cocoa application, which is what I am working on.

With that in mind, how would I go about using NSLog to output some final debugging messages when my application exits?

To be specific, I would like to do something like this:

int myDebugVariable = 0;

int main(int argc, char *argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    CMLog(@"application begin");

    int exitCode = NSApplicationMain(argc,  (const char **) argv);

    CMLog(@"application end. Debugging variable = %d", myDebugVariable);

    [pool release];
    return exitCode;
}

In this example, The "application begin" line is printed to the console, but the "application end." line is not.

Note #1: In my actual code, I am using something more sophisticated than myDebugVariable. This is a simplified example that illustrates the effect I am trying to achieve.

Note #2: I am familiar with the ApplicationWillTerminate method, which gets called when the application is about to quit, but it does not suit my needs. My debugging code relies on the dealloc methods for some custom classes, so it does not come into play until after ApplicationWillTerminate is called.


update:

Adam Rosenfield's answer did the trick. For the sake of completeness, here is a working solution:

int myDebugVariable = 0;

void my_exit_handler(void)
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    CMLog(@"application end: Debugging variable = %d", myDebugVariable);

    [pool release];
}

int main(int argc, char *argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    CMLog(@"application begin");
    atexit(my_exit_handler);

    int exitCode = NSApplicationMain(argc,  (const char **) argv);

    [pool release];
    return exitCode;
}
+1  A: 

Use atexit(3) to register an exit handler. It will automatically be invoked when your app exits, either by finishing main or by calling exit(3). For example:

void my_exit_handler(void)
{
    NSLog(@"about to exit, x = %d\n", x);
}

// at some point during app initialization...
atexit(&my_exit_handler);
Adam Rosenfield
I had to add another NSAutoreleasePool in my_exit_handler for this to work, but it definitely did the trick. Thank you!
e.James