Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a variable be passed into an NSMenu action?

I am dynamically building menu's based on an array and there is a sub-menu is linked to an IBAction which opens a folder in Finder. The folder it opens is based on a property of the object in my initial array.

Is there a way of linked the NSMenuItem action to the IBAction and passing in this directory variable as I am dynamically creating this array?

OR should I be going into the IBAction and resolving the directory by referencing the NSMenuItem with against array?

e.g.

person = [[Person alloc] init];
// person is assigned
subMenu = [[NSMenu alloc] init];
[subMenu addItemWithTitle:@"Open folder" action:@selector(openDirectory:person.directory) keyEquivalent:@""];
like image 325
Coderama Avatar asked Mar 08 '12 07:03

Coderama


2 Answers

This is what I was after.

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);
like image 167
Coderama Avatar answered Nov 05 '22 17:11

Coderama


An action only takes a "(id) sender" parameter, where the object that called the action is supposed to be sent.

But if your action method lives in some Objective C object (and not a singleton or whatever), you can easily reference that object's properties from your action.

Hopefully this is clear to you or if not, show a bit of your IBAction code and tell us where it lives and how it's declared.

like image 24
Michael Dautermann Avatar answered Nov 05 '22 19:11

Michael Dautermann