Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa - How to pass a parameter with NSMenuItem's action?

I am creating a menu programmatically:

+ (void)refreshStatusMenu {
    for (NSDictionary *dict in kbMsgSet) {
        NSString *msj = [dict objectForKey:@"msj"];
        NSString *mid = [dict objectForKey:@"mid"]; // <- this would be http://www.blah.com 

        msg_item = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"%@", msj] action:@selector(goToURL:mid:) keyEquivalent:@""];

        [msg_item setTarget:[self class]];
        [sm insertItem:msg_item atIndex:(i_msg)];
        i_msg++;
        //...
    }
}

How do I pass a parameter to @selector(goToURL:), so that on item-click I could call:

+ (void)goToURL:(id)obj {
    NSLog(@"Open url:...%@", obj);
}

If I try passing @selector(goToURL:var2:) I get uncaught exception error.

like image 533
janeh Avatar asked Oct 02 '12 01:10

janeh


1 Answers

You can't have 2 parameters to an action method. There should only be one, the sender, which in this case would be the menu item. See the answer to this question for a way to attach extra information to a menu item and retrieve it in the action method.

like image 175
JWWalker Avatar answered Nov 06 '22 08:11

JWWalker