Search code examples
objective-ccocoaactionnsmenuitem

Connecting NSMenuItems with Actions & vice versa


Let me explain what I mean :

Let's say we have a menu with several items in it (let's say it's a... collection of options, only one of which may be enabled at any time).

What is the suggested implementation (bindings? I don't know...), so that I could satisfy the scenarios below :

  • The user clicks an item on the menu, and this triggers the action doSomething on some controller. Also, when the action doSomething is called independently, the appropriate menu item should be checked, as well.

  • We have an identical menu (somewhere else) with the same options as the initial menu. The user clicks on an item of menu A, the same item is checked on menu B, the action doSomething is performed. This should work in any order of actions (A->B->action, B->A->action, action->A->B)


Solution

  • -doSomething: should set a BOOL variable indicating whether or not the menu items should be checked.

    The, use the NSUserInterfaceValidations protocol, just as I explained in an answer to your previous question.

    In -validateUserInterfaceItem:, get the value of that BOOL, then:

    [(NSMenuItem*)anItem setState:(boolValue ? NSOnState : NSOffState)];