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

Note: There is nothing special about the Preferences menu item. This is merely an example of the more general case of automatic menu item enabling for menus.

To enable this menu item two conditions must be met:

  • Your controller object needs to declare and implement an IBAction or action method.

  • The NSMenuItem must be "connected" to the action method of your controller object. You can do this in Interface Builder or programatically.

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
{ }

Back to Top 

Set Target-Action Connection

Using Interface Builder

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

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

Back to Top 

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:)];
}

Back to Top 

Related Documentation

Back to Top 

Document Revision History

DateNotes
2008-01-21First Version

Posted: 2008-01-21


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.