Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to setup target/action for NSMenuItem in Cocoa?

I'm having some real difficulty with some initial Cocoa programming I am carrying out.

Essentially, I have an NSStatusBar item with an NSMenu attached as the menu. The menu has a single NMMenuItem. In IB I have connected the NSMenuItem to an NSObject which itself is set to the ApplicationDelegate's class; I have then set the Received Actions to an IBAction method in the ApplicationDelegate. Everything is hooked up correctly I think, except when I run the program and click the menu item the IBAction method is not called. I really can't seem to work it out. Here is the relevant code.

Application Delegate h file:

#import <Cocoa/Cocoa.h>

@interface sssAppDelegate : NSObject <NSApplicationDelegate> {
    IBOutlet NSMenu *statusMenu;
    NSStatusItem *statusItem;
}

- (IBAction)showPreferencePanel:(id)sender;

@end

Application Delegate m file:

#import "sssAppDelegate.h"
@implementation sssAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application 
}

-(void)awakeFromNib{
    statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
    [statusItem setMenu:statusMenu];
    [statusItem setTitle:@"Status"];
    [statusItem setHighlightMode:YES];
}


- (IBAction)showPreferencePanel:(id)sender {
    NSLog(@"Hello World!");
}

@end 

As I say, in IB I have connected the NSMenu to statusMenu in the Application Delegate (thus the menu all shows up under the NSStatusBar), and I have connected an NSMenuItem within the NSMenu to the NSObject with the Application Delegate class, and hooked it up to call showPreferencePanel, but nothing happens when I run it!!!

I tried it programatically as well but still can't get the IBAction method to be called.

Edit: I would attach some screen grabs to show the setup in IB but I'm not yet allowed.

The main nib which contains the menu that is added to the NSStatusBar, it looks like this:

  • FO NSApplication
  • FR FirstResponder
  • Application NSApplication
  • Font Manager NSFontManager
  • Main Menu NSMenu
    • Menu Item (Preferences) NSMenuItem
  • Sss App Delegate sssAppDelegate

NSMenuItem:

  • Sent Actions - showPreferencePanel--->Sss App Delegate

Sss App Delegate:

  • Outlets - statusMenu--->Main Menu
  • Received Actions - showPreferencePanel:--->Main Item (Preferences)
like image 516
Edwardr Avatar asked Mar 05 '11 19:03

Edwardr


1 Answers

Programmatically, have you tried :

[statusItem setTarget:someTarget];
[statusItem setAction:@selector(someSelector)];

It should work.

like image 105
Jean Avatar answered Nov 05 '22 05:11

Jean