How to pass data to action in #selector?

Hi, I would like to add a menu item and in the action's #selector I am specifying a method, but if such method has arguments then I get errors.


How to work around this?

Replies

Well, you can't, since there's nowhere that the values for the arguments can come from. (Every choice of a specific menu item is the same as every other choice of the same menu item.)


Depending on platform (macOS vs iOS), you must/can specify a "sender" parameter to the action method. One way to get additional information is to look at the sender, and use that object to find custom values (if, say, you subclass the UI element to provide this information).


But it's hard to be specific without knowing what kind of data (i.e. where it comes from) you're talking about.

A simple way to achieve the result is :

- either to set the argument as tag of the menuItem (if the argument is simply an Int)

- or create a var in the application at global scope that you set before calling the menu item and use in the action. That's the way I'm doing it.

If the sender is a menu item, I like to set a representedObject for the menu item. The representedObject can be a dictionary or just about any other kind of object.