8

Can I use the item's tag attribute to store a special key/ID or is it meant for something else?

Example of intended use:

  - (void)awakeFromNib {

    [self.popup addItemWithTitle: [NSString stringWithFormat: @"dummy title" ]];
    [[self.popup lastItem] setTag: 1658 ];
  }

  - (IBAction)popupAction: (id)sender {

    [self someMethod: [sender selectedItem].tag];

  }

2 Answers 2

8

yeah the tag of all controls is free for your devious use, you may use different numbers for different items, or to identify them as a kind of item, it is up to you.

2
  • 4
    Just don't use zero, if you also want to have separatorItems in your menu.
    – iforce2d
    Commented Dec 12, 2013 at 15:24
  • 2
    Official NSMenuItem docs site has very helpful para about it which starts like The menu item's tag. and there endeth the para.
    – thevikas
    Commented Oct 27, 2017 at 14:56
3

As the documentation says:

You typically assign tags to menu items from Interface Builder, but you can also assign them programmatically using the setTag: method of NSMenuItem.

For further details, read the Application Menus and Pop-Up Lists and User Interface Validation guides. But the basic idea is that Cocoa doesn't care what you put there.

I believe the intended purpose is to let you loosely couple parts of your code together—the code that validates user actions doesn't have to know how your interface is designed, and your interface doesn't have to know anything about the validator; they just have to agree on a number. However, in modern Cocoa, it's just as easy, and even more loose, to just look at the action, so the tag is freed up for anything you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.