Search code examples
cocoansmenuitem

Using validateMenuItem on lots of items


This is a best-practices question:

I have a number of menu items that toggle depending on the number of rows selected in the associated NSTableView. For instance, "Connect ends" should only be allowed when there are two lines selected, not zero, not one, only two.

My question is how to refer to these in the validateMenuItem. I know the action method sends in the menuItem and I could select on, say, the title text. But does this work when the app is localized? I could also use the tag, but tags are "non standard" in some respects, and it would be all too easy to forget to set them.

So what is the best/easiest-to-maintain solution for this problem?


Solution

  • Title text is not safe, as you said, because it is likely to change for whatever reason.

    A safer method is to access the NSMenuItem's action, and comparing it to a @selector literal

    Like this:

       if ( [menuItem action] == @selector(connectEnds:) )
       {
          //Do your check to figure if you should return YES/NO here to validate the menu item
       }