views:

50

answers:

2

Hello Everyone.

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 *tempURL   = [NSURL  URLWithString:[NSString stringWithFormat:@"http://www.reddit.com%@", [[message objectForKey:@"data"] objectForKey:@"context"]]];

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

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.

Chuck
OK, but how would I associate the URL with each menu item?
+1  A: 

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
Georg Fritzsche
I tried this and although it doesn't error out it doesn't quite work, either. I tried your suggestion with the following method declaration.[code]-(IBAction)menuLoadMessage:(id)sender{ [self loadMessage:[sender representedObject]];}-(void)loadMessage:(NSURL *)messageUrl{ [[NSWorkspace sharedWorkspace] openURL:messageUrl];}[/code]
@user: Did you use `-setRepresentedObject:` on the items?
Georg Fritzsche
NSURL *tempURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.reddit.com%@", [[message objectForKey:@"data"] objectForKey:@"context"]]]; [tempItem setRepresentedObject:tempURL];[tempItem setAction:@selector(menuLoadMessage:)];
user312867: Is that code running (i.e., is the method/block/compound statement it's in being called)? Have you verified that `tempItem` is not `nil`?
Peter Hosey
Nice. Ok that worked. I wasn't setting the target of the to self. What is the logic behind doing that? I am sorry.....so new to this...
@user: The instance of menu-item doesn't know what instance creates it. Even if it did, we do not always want it to call `self`, we might set different objects as targets - e.g. `-terminate:` on `NSApp` when *"Quit"* was clicked.
Georg Fritzsche
OK, perfect. Thank you all.