Search code examples
objective-cdynamicadditionnsmenuitemnsmenu

Creating dynamic count of NSMenuItems


I'm currently struggling with dynamic UI in Mac OS X. I created a Menu Bar item and want to add a dynamic count of MenuItems within it.

The count of the elements depends on Network interfaces on the computer. My Mac got two Interfaces, another got maybe just one or three.

The creation of the Elements is not the Problem. But I want to refer to the elements in later code.

-(void)addItems
{
    NSMenuItem *menuItem = [menu addItemWithTitle:@"Start" action:@selector(click:) keyEquivalent:@""];
}

Then I want to update the Title of the element:

-(IBAction)click:(id)sender
{
    [menuItem setTitle:@"Clicked!"];
}

Of cause, the "click" Action returns an undeclared identifier (menuItem). The Problem is, that I can't declare them in the header file, because they are dynamic and they probably could reach a count of 100 items so I can't declare like 10 items and use them or not.

How do I deal with these situations? Hope, you can help me!

Greets, Julian


Solution

  • Just ran into this problem and it's pretty simple. You could manually keep track of your NSMenuItem pointers, but the easiest way is to use tags. When you create the menu item, do this:

    item = [subMenu addItemWithTitle:@"A1" action:@selector(testing123:) keyEquivalent: @""];
    [item setTag:23];
    

    And then in your delegate:

    -(IBAction)testing123:(id) sender
    {
        NSMenuItem * item = (NSMenuItem*)sender;
        int cmdVal = [item tag];
        printf("Testing123 - %d\n", cmdVal);
    }
    

    And that's it. Just add 10 items and give them all a different tag. Cheers!