How to have NSMenu with dynamic actions

I want to create NSMenu with a parameter similar to the "Send" parameter, which you will find in Windows Explorer, which will indicate the device to which you can send the file.

From my research, it seems that it is impossible to define a selector that also sends a function parameter, so this is not a case of availability @selector(@"sendToVolume:1"). So, how else can I configure the menu for another task, based on which the element is clicked when the number of elements is unknown?

+5
source share
2 answers

NSMenuItem has a property representedObjectthat can be used to store everything you need, for example, a link to the destination that represents this element.

When the selector is called, you can return the represented object back:

-(IBAction)sendTo:(id)sender {
    id destination = [sender representedObject];
}
+15
source

But you can use selectors with parameters! NSObjecthas three methods defined as follows:

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

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

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

then you can use it as follows:

[appController performSelector:@selector(sendToVolume:) 
               withObject:[NSNumber numberWithInt:1]];
+1
source

All Articles