views:

100

answers:

4

I just want to quit as fast as possible, before the nibs are loaded. I tried [NSApp stop:self] but that didn't seem to work. Is there a better way than getting my process and killing it?

(I know it's a weird thing to do. It's for a good reason.)

+2  A: 

Without knowing more, I'd say put the checking code into main() before invoking NSApplicationMain

int main(int argc, char **argv)
{
    if(shouldExit() == YES)
    {
        exit(exitCode);
    }

    return NSApplicationMain(argc, (const char **) argv);
}
nall
You could also do this. :)
Marc W
If `shouldExit()` uses Cocoa frameworks, you may end up leaking autoreleased objects since there is no `NSAutoreleasePool` in place.
Barry Wark
+3  A: 
[[NSRunningApplication currentApplication] terminate];

Apple docs here. You can also use forceTerminate. You could also use nall's suggestion, but it will only work if you can do the work to check if the app needs to be terminated in main(). Otherwise, you'll need to do something more along the lines of what I suggested.

Marc W
You could also do this. :)
nall
I'm pretty sure that by the time you can call this method, at least the app's main menu NIB will have been loaded.
Barry Wark
He could call it from his `NSApplicationDelegate` class before nibs are loaded (such as from `applicationWillFinishLaunching`).
Marc W
When you call terminate: it goes about making sure you really want to terminate, which isn't suitable for my task. It might be useful for someone else, though.
zekel
A: 

This should work:

[[NSApplication sharedApplication] terminate: nil];

Reference

Erator
Calling this method will initialize the shared app, and thus at least MainMenu.nib (or whatever the main menu NIB of the app is called) will get loaded.
Barry Wark
A: 

If you can detect that you want to quit easily, modifying the main() function of your app is the "fastest" place:

int main(int argc, char **argv)
{

  id pool = [[NSAutoreleasePool alloc] init]; //needed if shouldExit() uses Cocoa frameworks

 @try {
    if(shouldExit())  {
      exit(0); //appropriate exit code, depending on whether this "fast" exit is normal or exceptional
    }
  }
  @finally {
    [pool drain];
  }

  return NSApplicationMain(argc, (const char **) argv);;
}
Barry Wark
Not sure if this matters, but shouldn't the pool be drained before the call to `NSApplicationMain()`? Or does it not matter?
Marc W
I don't think it matters. NSApplicationMain will just push another autorelease pool onto the pool stack.
nall
As written, you're right that there's a potential memory leak if NSApplicationMain() throws an exception. Since the app will be quitting anyways, it's not really an issue. I'll modify things anyways, though.
Barry Wark
@MarcW, if shouldExit() creates a lot of autoreleased objects, then it would probably make sense to drain the pool before calling NSApplicationMain or those instances will just hang around until the program exists.
Barry Wark