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:
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 { } |
Set Target-Action Connection
Using Interface Builder
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
For the same issue with Carbon applications please refer to: Technical Q&A 1079.
Introduction to Application Menus and Pop-up Lists, specifically the "Enabling Menu Items" section.
Document Revision History
Date | Notes |
---|---|
2008-01-21 | New document that describes the two things you need to implement to enable the "Preferences" menu item on Mac OS X. |
Copyright © 2008 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2008-01-21