Is it possible to pass a variable to an NSMenu action?

I am dynamically creating a menu based on an array, and there is a submenu associated with IBAction that opens a folder in Finder. The opened folder is based on the property of the object in my initial array.

Is there a way to associate an NSMenuItem action with an IBAction and pass in this directory variable as I dynamically create this array?

OR should I go to IBAction and resolve the directory, referencing NSMenuItem as an array?

eg.

person = [[Person alloc] init]; // person is assigned subMenu = [[NSMenu alloc] init]; [subMenu addItemWithTitle:@"Open folder" action:@selector(openDirectory:person.directory) keyEquivalent:@""]; 
+4
source share
2 answers

The action accepts only the " (id) sender " parameter, where it is assumed that the object causing the action should be sent.

But if your action method lives in an Objective-C object (and not in a single or any other), you can easily refer to these properties of the object from your action.

I hope this is clear to you or not, show a little of your IBAction code and tell us where it lives and how it is declared.

+3
source

This is what I was.

 NSMenuItem *menuItem; menuItem = [subMenu addItemWithTitle:@"Open folder" action:@selector(openDirectory:person.directory) keyEquivalent:@""]; [menuItem setRepresentedObject:person]; 

Then in my IBAction I did something like this to extract the directory:

 - (IBAction)openDirectory:sender { Person *person = [sender representedObject]; NSLog(@"directory: %@",person.directory); 
+3
source

Source: https://habr.com/ru/post/1400344/


All Articles