cocoarecursionnsmenunsmenuitem

Searching NSMenuItem inside NSMenu recursively


The method itemWithTitle locates a menu item within a NSMenu. However it looks only inside the first level. I cannot find a ready-to-use method that will do the same job recursively by searching inside all the nested submenus. Or, somehow equivalently, a function that swipes NSmenu's recursively.

It looks quite incredible to me that such a thing would not exist. Maybe there is some function not directly related to NSMenu that can come in handy?


Solution

  • Ok, since I really need to do this clumsy workaround for a number of specific reasons (beyond the scope of this post, and quite uninteresting anyway) I ended up coding it myself.

    Here is the snippet:

    NSMenuItem * mitem;
    
    while (mitem) { // loop over all menu items contained in any submenu, subsubmenu, etc.
    
         // do something with mitem ....
    
         mitem = next_menu_item(mitem);
    }
    

    which is powered by the functions:

    NSMenuItem * goto_submenu(NSMenuItem * mitem){
    
        NSMenu * submen = [mitem submenu];
        if (submen && [[submen title] isNotEqualTo:@""] && [submen numberOfItems])
            return goto_submenu([submen itemAtIndex:0]);
    
        return mitem;
    };
    
    NSMenuItem * next_menu_item(NSMenuItem * mitem){
    
        NSMenu * menu = [mitem menu];
    
        if ([menu indexOfItem:mitem]==([menu numberOfItems]-1)) //if is last item in submenu go to parent item
            return [mitem parentItem];
    
        return goto_submenu([menu itemAtIndex:([menu indexOfItem:mitem]+1)]);
    };