views:

2019

answers:

3

Hey all,

I want to incorporate an applicationDidFinishLaunching: into my cocoa delegate. How would I do this?? On the iphone SDK the applicationDidFinishLaunching is already in the application delegate, but when making my mac application I noticed that there were none.

Best Regards,

Kevin

+3  A: 
- (id)init
{
    if (self = super init]) {
        [NSApp setDelegate:self];
    }
    return self;
}

You can also do this in Interface Builder; from "File's Owner" in MainMenu.xib, just drag the "delegate" outlet to your object. You may want to consider using -awakeFromNib instead though.

Michael
You are missing an angle bracket around `super init` and you don't mention that the method `applicationDidFinishLaunching:` must be implemented by the ssame class to make it work.
MKroehnert
+12  A: 

As of Xcode 3.2, the Mac application template also comes with an application delegate, already connected, that has such a method.

To set this up in a project created before Xcode 3.2, create a new class for your delegate to be an instance of. I usually name mine “AppDelegate”. You'll do this by right-clicking on the Classes group and choosing “Add File”, then picking the Cocoa NSObject Subclass file template.

Open the header you just created (AppDelegate.h). Give it any instance variables you want. Then hit Go to Counterpart (⌘⌥⇡). That takes you to the implementation file (AppDelegate.m). Add your applicationDidFinishLaunching: instance method here. Unlike on the iPhone, this is a notification-handler method, so it takes an NSNotification instance and not an NSApplication instance.

Now to hook it up. In the Resources group, open MainMenu.nib. Drag an Object from the Library window into the top-level nib window (the one with icons in it, such as File's Owner and First Responder). Select the object you just created and open the Identity inspector (⌘6—memorize the numbers of the Inspector tabs; it'll save you a lot of time). Set the object's class to AppDelegate, matching the name you used in Xcode. Right-click on the File's Owner, and drag from its delegate outlet to your new object.

In Xcode, add an NSLog statement to your applicationDidFinishLaunching: method. Hit Save All, then Build and Go. Switch back to Xcode and open the Run Log (⇧⌘R). If you did everything right and I didn't forget anything, you should see the log message there.

Peter Hosey
A: 

Hi Kevin. Were you missing the application delegate files altogether? It seems as though there's a bug in the Xcode installation scripts (at least for 3.2.1 on Snow Leopard) that installs the latest project templates in the wrong folder. The older template for a "Cocoa Application" project doesn't contain the delegate files.

I've explained what I've discovered (and how I "fixed" it) in a blog post called Fixing the Xcode Project Templates.

Cheers, Graham

Graham Ashton