Next: 3.5 Creating sub-menus Up: 3 Menus Previous: 3.3 Our First Application

3.4 Fun with NSMenuItem's target

The next step in our tutorial is to add to the menu an item which prints Hello! to the user when the user selects the item.

So, we add a new menu item to our menu, invoking the printHello: action (which we'll implement in our custom object):

[menu addItemWithTitle: @"Print Hello"  
      action: @selector (printHello:)  
      keyEquivalent: @"h"];
Since our custom object is the application's delegate, we don't need to set explicitly the target: the library can determine it at run-time. In other cases it could be necessary to set a different target, as in:
NSMenuItem *menuItem;
id myObject;

// <missing code: create myObject etc>

menuItem = [menu addItemWithTitle: @"Print Hello"  
                 action: @selector (printHello:)  
                 keyEquivalent: @"h"];
[menuItem setTarget: myObject];

But in this case, we don't need to set the target explicitly, and the code is simply:

#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>

@interface MyDelegate : NSObject
- (void) printHello: (id)sender;
- (void) applicationWillFinishLaunching: (NSNotification *)not;
@end

@implementation MyDelegate : NSObject 
- (void) printHello: (id)sender
{
  printf ("Hello!\n");
}

- (void) applicationWillFinishLaunching: (NSNotification *)not
{
  NSMenu *menu;

  menu = AUTORELEASE ([NSMenu new]);

  [menu addItemWithTitle: @"Print Hello"  
        action: @selector (printHello:)  
        keyEquivalent: @""];

  [menu addItemWithTitle: @"Quit"  
        action: @selector (terminate:)  
        keyEquivalent: @"q"];

  [NSApp setMainMenu: menu];
}
@end

int main (int argc, const char **argv)
{ 
  [NSApplication sharedApplication];
  [NSApp setDelegate: [MyDelegate new]];

  return NSApplicationMain (argc, argv);
}
The GNUmakefile is the same. I hope you appreciate how easy and simple is coding in GNUstep; I encourage you to try it out and enjoy all the fun you of selecting the Print Hello menu item and see the program print out Hello!.



2008-01-16