Question

I have a nib (winA.xib) that contains a window. My app delegate contains an NSWindowController subclass called WinAController.

WinAController has a property (NSMenu *mainMenu) that I want to point to the MainMenu. I have set it after I instantiate WinAController with this code:

    WinAController = [[WinAController alloc] initWithWindowNibName:@"WinA"];
    WinAController.mainMenu = [NSApp mainMenu];

I have a menu item underneath the "Window" top-level menu item on MainMenu that invokes the [WinAController showWindow] method and displays WinA. I want to toggle the on/off state of this menu item depending on whether WinA is visible or not. WinAController also has another property (NSMenuItem *myMenuItem).

How can I get a reference to a sub menu of the "Window" top-level menu item. The title of sub menu item I want to get is "Command". I have tried this:

    if (mainMenu != nil) {
    myMenuItem = [mainMenu itemAtIndex:[mainMenu indexOfItemWithTitle:@"Command"]];
}

But it doesn't seem to work.

Where am I going wrong?

Thanks,

Edit: I have now placed WinAController in mainMenu.xib. I have set WinA's (in winA.xib) File's Owner to be of class WinAController but I can't figure out how to hook up WinAController's window IBOutlet to WinA as they are in different nibs!

Was it helpful?

Solution

I thought I told you to put the Window Controllers in MainMenu.xib?

Oh well, nothing ventured, nothing gained. What you want to do, of course, is the following:

@interface MyApplicationDelegate : NSObject {
  IBOutlet NSMenuItem *winAMenuItem;
}

@property(assign) IBOutlet NSMenuItem *winAMenuItem;

@end

Then you can access this through [[NSApp delegate] winAMenuItem];

OTHER TIPS

You can store a reference to your menu item directly, possibly via IBOutlet in your main nib.

Or (better, IMO), you can implement -validateMenuItem: in WinAController and set the state there (that way, the state is only set when the user will actually see it, too):

- (BOOL)validateMenuItem:(NSMenuItem *)item {
    if ([item action] == @selector(showWindow:)]
        [item setState:[winA isVisible] ? NSOnState : NSOffState];

    return YES;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top