开发者

Cocoa - Pass parameter for setAction

开发者 https://www.devze.com 2023-01-04 11:48 出处:网络
I thought I\'d try my hand at creating a simple cocoa app.It is a simple inbox notifier for reddit.I am bringing in a bunch of URLs and would like to make menu items for each URL with a link to the pa

I thought I'd try my hand at creating a simple cocoa app. It is a simple inbox notifier for reddit. I am bringing in a bunch of URLs and would like to make menu items for each URL with a link to the page. I 'd like to set the actions of each, dynamically. I need to pass the URL to the method, so it knows where to go. I have a feeling I am doing this all wrong. Can someone point me in the right direction. I'd like to just create an NSURL and send it to loadMessage.

NSURL *开发者_如何学CtempURL   = [NSURL  URLWithString:[NSString stringWithFormat:@"http://www.reddit.com%@", [[message objectForKey:@"data"] objectForKey:@"context"]]];

[temptItem setAction:@selector(loadMessage:messageUrl:)];


That selector isn't a valid action message. Actions can accept either one argument or none; if they accept one argument, the object passed in the argument will be the control that sent the message.

What you need to do is create a method in your controller that calls your loadMessage:messageURL: method with the correct objects.


As Chuck said, that selector has the wrong form. One way to do it is to use -representedObject to e.g. associate the item with an URL:

- (void)menuAction:(id)sender {
    [[NSWorkspace sharedWorkspace] openURL:[sender representedObject]]; 
}

// adding an item:
NSURL *url = [NSURL URLWithString:@"http://google.com/"];    
NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:@"moo" 
                    action:@selector(menuAction:) keyEquivalent:@""] autorelease];
[item setTarget:self];
[item setRepresentedObject:url];
[item setEnabled:YES];    
// insert into menu
0

精彩评论

暂无评论...
验证码 换一张
取 消