Search code examples
cocoansmenu

How to have an NSMenu with dynamic actions


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?


Solution

  • 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];
    }