Technical Q&A QA1552

Enabling the application menu's "Preferences" menu item on Mac OS X

Q:  How do I enable the application menu's "Preferences" menu item on Mac OS X?

A: How do I enable the application menu's "Preferences" menu item on Mac OS X?

For the "Preferences" menu item to be enabled in a Cocoa application you must setup the target-action mechanism or the communication between the NSMenuItem and your controller object.

To enable this menu item two conditions must be met:

If you do not meet both conditions, then the Preferences menu item will remain disabled.

Define The Action Method

The action is the message your NSMenuItem sends to the target or, from the perspective of the target, the method it implements to respond to the action. You need to declare this method in your .h header file and implement it in your .m source file.

Listing 1  Example action method

-(IBAction)openPreferences:(id)sender { }

Set Target-Action Connection

Using Interface Builder

Figure 1  Connecting NSMenuItem to your IBAction method: control drag from the menu item to your object.

Using Code

Although using Interface Builder is the straight forward way, you can do the same thing using code.

Listing 2  Setting the target and action with code.

NSMenu *menu = [[[[NSApplication sharedApplication] mainMenu] itemAtIndex:0] submenu]; 
NSString *prefsTitle = [NSString stringWithFormat:@"Preferences%C", (unichar)0x2026];
NSMenuItem *prefsMenuItem = [menu itemWithTitle:prefsTitle];
if (prefsMenuItem)
{
    [prefsMenuItem setTarget:self];
    [prefsMenuItem setAction:@selector(openPreferences:)];
}

Related Documentation



Document Revision History


DateNotes
2008-01-21

New document that describes the two things you need to implement to enable the "Preferences" menu item on Mac OS X.