Example code programming Objective-C with Cocoa in Xcode and Interface Builder (Leopard)

2: Example: Menu Item

Implementing a simple Menu item

In XCode: File->New Project->Cocoa Application

Call it: MenuApp

Next do: File->New File and choose Objective C Class.

Call the files MyMenuController.h and MyMenuController.m, code them as shown below and save. Note these are subclassed as NSMenu.

// MyMenuController.h // MenuApp #import <Cocoa/Cocoa.h> @interface MyMenuController : NSMenu { } - (IBAction)doIt:(id)pId; - (IBAction)doItAgain:(id)pId; @end // MyMenuController.m // MenuApp #import "MyMenuController.h" @implementation MyMenuController - (IBAction)doIt:(id)pId; { NSLog(@"Hi there"); } // end doIt - (IBAction)doItAgain:(id)pId; { NSLog(@"Hi there Again"); } // end doItAgain @end

Now bring up Interface Builder by double clicking on MainMenu.nib in the Resources section of MenuApp

Drag a Menu onto the menu bar, then click on it and drag another menu item onto the drop down list of items.

Rename the items to 'Do it' and 'Do it again' by double clicking each item in turn and changing the selected text.

Choose MyMenuController from the Class menu in the Inspector

Interface Builder, NSMenu menu items and class identity

Interface Builder showing the NSMenu menu with menu items and the object class in the Inspector

Choose the Connections display in the Inspector and drag from the connection circle next to the Action 'doIt' to the button you dragged onto the window.

You will see a label pop-up as shown in the picture below.

Let go the mouse button and the display will change as shown.

Interface Builder, NSMenu menu items, and linking action to item

Interface Builder showing linking action with menu item

Save Interface Builder.

Return to XCode. Choose Run->Console. Now Build and Run.

You will see 'Hi There' appear in the Console log.

Interface Builder, NSMenu menu items the working menu

Interface Builder showing the working menu item

If you want to download the code

Click the Download Link to obtain 002-MenuApp.zip file of this whole OS X 10.5 Leopard program.

Download 002-MenuApp.zip (2.3 MB)

Please send me your comments

If you include your e-mail I may reply!  

Page last modified: 18:58 Sunday 12th. May 2013

Julius Guzy

Paintings & Drawings

  • Wind in the trees at Roe Valley park