Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have an NSMenu with dynamic actions

Tags:

cocoa

nsmenu

I want to create an NSMenu with an option similar to the Send To option you'd find in Windows Explorer where it will list the devices attached that you can send the file to.

From my research it seems that it's not possible to define a selector that sends a parameter to the function as well, so it's not a case of having @selector(@"sendToVolume:1"). So how else could I have the menu perform a different task based on which item is clicked when the number of items is unknown?

like image 877
Septih Avatar asked Sep 08 '09 09:09

Septih


2 Answers

NSMenuItem has a representedObject property, which can be used to store anything you'd like, such as a reference to the destination that item represents.

When the selector is invoked, you can then get the representedObject back:

-(IBAction)sendTo:(id)sender {
    id destination = [sender representedObject];
}
like image 88
iKenndac Avatar answered Oct 30 '22 19:10

iKenndac


But you can use selectors with parameters! NSObject has three methods defined like this:

-performSelector:
-performSelector:withObject:
-performSelector:withObject:withObject:

Now, the first is like having @selector(someMethod:), but the last two are used to send parameters to the selector. For example:

-(void)sendToVolume:(NSNumber)nr { 
//do stuff
}

then you could use it like this:

[appController performSelector:@selector(sendToVolume:) 
               withObject:[NSNumber numberWithInt:1]];
like image 37
Woofy Avatar answered Oct 30 '22 20:10

Woofy