简体   繁体   中英

Application Delegate - Cocoa

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

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. 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 Debugger Console. If you did everything right and I didn't forget anything, you should see the log message there.

- (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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM