Using NSMenu outside the NIB
For an Application concept I'm trying out (which I named 'Tarantula'), I needed to load menus dynamically, they would not be defined inside a NIB file. So I ended up with code like the following:
NSMenu *menu; NSMenuItem *menuItem; [NSApp setMainMenu:[[NSMenu alloc] init]]; menu = [[NSMenu alloc] initWithTitle:@""]; [menu addItemWithTitle:@"About Tarantula" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""]; [menuItem setSubmenu:menu]; [[NSApp mainMenu] addItem:menuItem]; [NSApp setAppleMenu:menu]; // Help menu menu = [[NSMenu alloc] initWithTitle:@"Help"]; [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Tarantula Help" action:@selector(showHelp:) keyEquivalent:@"?"] autorelease]]; // Help menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease]; [menuItem setSubmenu:menu]; [[NSApp mainMenu] addItem:menuItem];
Sadly this doesn't work, for several reasons. NSApp's -setAppleMenu: is no longer defined, but can still be used by including the following code:
@interface NSApplication (NiblessAdditions) -(void) setAppleMenu:(NSMenu *)aMenu; @end
Then, whatever I tried (and again I'm using it outside the AppDelegate's awakeFromNib) I ended up with either a blank menu or an additional apple () menu appeared. Finally I concluded I should leave whatever was created by the NIB and I replaced:
[NSApp setMainMenu:[[NSMenu alloc] init]];
by:
[[NSApp mainMenu] removeAllItems];
after which everything started working.
So now for the end result. When the application starts, at first you'll see just the Application or Apple menu:

Then once the menu is replaced you'll see:

Which I think this isn't disturbing for the eye.
