Search code examples
cocoamacosnsmenuitem

NSMenuDelegate questions


I have an NSMenu which contains both static and dynamically created NSMenuItem's (static meaning NSMenuItem's created in Interface Builder, dynamic meaning NSMenuItem's created at run-time). Although I'm developing on 10.6, my application also offers 10.5 support.

My menu consists of a number of dynamic NSMenuItem's which contain submenus. Currently, I'm using NSMenuItem's parentItem: method (exclusive to 10.6) to grab the parent menu item when a submenu item is clicked.

EDIT: Here's a crude attempt at creating a manual parentItem: method, but it's not particularly intuitive. Surely there's a better way?

- (NSMenuItem *)findParentByChild:(NSMenuItem *)child {
    for(int x = 0; x < [statusBarMenu numberOfItems]; x++) {
        // Avoid any statically created menu items
        if([[statusBarMenu itemAtIndex:x] tag] != 100) {
            NSMenu *submenu = [[statusBarMenu itemAtIndex:x] submenu];
            if(submenu != nil) {
                for(int y = 0; y < [submenu numberOfItems]; y++) {
                    // This looks like our parent
                    if([submenu itemAtIndex:y] == child) {
                        return [statusBarMenu itemAtIndex:x];
                    }
                }
            }
        }
    }
    return nil;
}

What's the best way to go about achieving this in a way that's 10.5 and 10.6 compatible?


Solution

  • You're saved: -menuNeedsUpdate: has been available since 10.3. :-)

    Available in Mac OS X v10.3 and later. Available as part of an informal protocol prior to Mac OS X v10.6.

    I use it heavily in an application that targets 10.5/10.6.

    Note: This answer pertains to an earlier version of the question concerning availability of -menuNeedsUpdate: