views:

58

answers:

1

I have a class in my application which handles all the controls and all the functions and variables are stored in it. How can I add a function which handles the application startup to it?

So basically I need to handle 'applicationDidFinishLaunching' in my class as well as in the application delegate.

How do I do that?

+5  A: 

NSApplication sends the NSApplicationDidFinishLaunchingNotification notification, so you should just be able to register for that in your class:

- (void)awakeFromNib
{
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self
           selector:@selector(appDidLaunch:)
               name:NSApplicationDidFinishLaunchingNotification 
             object:nil];
}

- (void)appDidLaunch:(NSNotification*)notification
{
    NSLog(@"Blast off!");
}

There's a general pattern here, in that Cocoa classes that have delegate methods with a method signature that passes a single notification parameter, such as the ‑(void)applicationDidFinishLaunching:(NSNotification*)notification delegate method of NSApplication, will also post a notification when the delegate method is called.

For example, NSWindow has a lot of delegate methods with this kind of signature, such as:

- (void)windowDidResize:(NSNotification *)notification

If you look at the docs for this method, you'll see that the notification that is passed to this delegate method is a NSWindowDidResizeNotification. You can then find more detail about this notification in the notifications section of the NSWindow docs.

This type of delegate method is often used when there is a likelihood that more than one object will be interested in the delegate information.

Rob Keniger