Search code examples
objective-ccocoansmenuitemnsmenu

Getting NSMenuItem of NSMenu tree by title


I have an NSMenu (let's say the Main Menu), with lots of NSMenus in it, and NSMenuItems at different levels.

I want to be able to get the NSMenuItem instance specifying the tree path (with the title of the corresponding NSMenus/NSMenuItems in it).

Example :

Menu :

  • File
    • New
    • Open
      • Document
      • Project
    • Save
    • Save As...

Path : /File/Open/Document

How would you go about it, in the most efficient and Cocoa-friendly way?


Solution

  • I think that best way would be to obtain the NSMenuItem by specifying its title or, better, a custom defined tag.

    #define kMenuFileNew 1
    #define kMenuFileOpen 2
    
    NSMenu *menu = [[NSMenu alloc] initWithTitle:@"File"];
    NSMenuItem *item1 = [[NSMenuItem alloc] initWith..];
    item1.tag = kMenuFileOpen;
    [menu addItem:item1];
    
    
    NSMenuItem* item2 = [menu itemWithTag:kMenuFileOpen];