views:

1209

answers:

1

I have declared a delegate for my cocoa application here :

MyAppDelegate.h

@interface MyAppDelegate : NSApplication {
}
- (void) applicationDidFinishLaunching:(NSNotification*) notice ;
@end

MyAppDelegate.m

@implementation MyAppDelegate 
- (void) applicationDidFinishLaunching:(NSNotification*) notice {
    NSLog(@"inside appdidfinishlaunching") ;
}
@end

I have linked the delegate outlet of File Owner to this object in IB.

Yet, this method is not getting called. I don't see any log messages from it.

Can you please suggest what is wrong ?

+4  A: 

Your application delegate is not an application itself. It should inherit from NSObject, not NSApplication.

Why that matters

NSApplication is a singleton. Its init method always returns the first instance of NSApplication or any subclass, throwing away any subsequent objects you (or the nib loader) may be calling init on.

So you ended up setting your application object as its own delegate. The object you intended to make the delegate died in the second call to init, and the application object took its place.

Changing the application object to be an instance of your subclass would also have worked, but you'd still have the application as its own delegate, which is unclean and possibly dangerous (NSApplication may privately implement some of its delegate methods itself, as they're just notification handler methods). The only correct solution is to make your app delegate class not inherit from NSApplication.

Peter Hosey
You nailed it. It works now. Can you explain why subclassing from NSApplication was not working ? Thanx.
euphoria83
I was going to actually say the same thing, but I couldn't think why it'd make sense to simply not work if you subclass NSApplication. Do you know why it fails, Peter?
Jason Coco
Yes. I edited my answer to include the explanation.
Peter Hosey
Peter, your explanations are always so clear! Thanks.
Abizern