Search This Blog

Thursday, January 26, 2012

Adding an Application Delegate in XCode 4.2

A lot of time I will create Cocoa projects (iOS is different to some degree) in XCode one way and later realize I need something that's not part of the standard project "Template."  Or, sometimes, you do something in XCode 4 that breaks the project.  For example, removing files the "wrong way" and not being able to get them "reinstalled" without weird compiler or other errors - so its basically faster to "start over."

In any case adding an "Application Delegate" is a common need as in needing an App Delegate to handle functions like "applicationDidFinishLaunching:"

To do this quickly add a new file with File>New>New File.

Create a Cocoa NSObject subclass - call it AppDelegate or something similar.

The .h file should look something like this:

@interface AppDelegate : NSObject<NSApplicationDelegate>
{
  // Put your app-level variables here...
}
@end

The .m similar to this:

@implementation ApplicationDelegate

// Add the code below to handle app startup items...
- (void)applicationDidFinishLaunching: (NSNotification *)aNotification
{
  // Init your app-level variables...
}
@end

In XCode 4.2 a "MainMenu.xib" is (always?) created along with the Cocoa project.  Open it in InterfaceBuilder by single-clicking.

Click the "Show Utilities" in the upper right to reveal the integrated Inspector area at the right (it should slide in from the right).

At the bottom select the "Object Library" (3-D black cube) and search for "Object."  The blue 3-D "Object" cube should appear along with several others.  Drag the blue object over into the area on the left holding other objects (under the black 3-D object cube with "main menu" and "font manager" under it).

Select it and rename its class (using "Custom Class" in the Inspector on the right) to "AppDelegate" or whatever you called your class above.  The object's name should change to "AppDelegate."

Right-click on the File's Owner so reveal the "hookup" menu.  Control-clock and drag from its delegate outlet to your newly named object.  If the hookup succeeds the menu will flash.

Save, build and go...

No comments:

Post a Comment