问题
I'm new to Obj-C/Cocoa programming, and I'm having an issue trying to dynamically add menu items to an NSMenu instance and have the items action selector already set upon insertion.
I can, add the dynamic menu items fine, but the action selector doesn't trigger when the item is clicked via the menu.
The first line below is the line of code I am using to add the menu item. You can set I'm setting the action:(SEL)aSelector to the "openEchowavesURL" function.
This function is in the same controller class file and I've included the function definition below.
Am I just calling the wrong selector syntax or someting? Or what is the trick to get the menu item to call a selector when clicked?
[statusMenu insertItemWithTitle:[NSString stringWithFormat:@"%d - %@", convo.newMessagesCount, convo.ewName] action:@selector(openEchowavesURL:) keyEquivalent:@"" atIndex:0];
- (void)openEchowavesURL:(id)sender {
// function details here
}
回答1:
If you want the action to be triggered against your object, you have to specify a target for the new NSMenuItem:
NSMenuItem *item = [statusMenu insertItemWithTitle:[NSString stringWithFormat:@"%d - %@", convo.newMessagesCount, convo.ewName] action:@selector(openEchowavesURL:) keyEquivalent:@"" atIndex:0];
[item setTarget:self]; // or whatever target you want
If you don't do it, then the NSResponder chain will be walked until an object responds to the selector.
回答2:
Actions need a target or else they get sent to nil and then new rules apply.
来源:https://stackoverflow.com/questions/1970135/adding-item-to-nsmenu-with-action-selector-preset