Reputation: 22820
I'm having a NSMenu
(application dock menu) and several items in it with the same action.
How can I figure out the index of the sender item (the one triggering the action) within its container menu? (I'm not interesting in the title
, since that might be a duplicate)
That's what I tried, but it keeps returning 0
(zero).
- (void)myAction:(id)sender
{
NSMenuItem* mi = (NSMenuItem*)sender;
int index = [[[mi parentItem] submenu] indexOfItem:mi];
NSLog(@"Clicked item with index : %d",index);
}
Any ideas? (Is there any better approach to achieve the very same thing?)
Upvotes: 1
Views: 2821
Reputation: 1713
Lookup the id of the sender in it's parent menu. A menu contains an array of it's menu items.
int indexOfMenuItem = [sender.menu.itemArray indexOfObject:sender];
indexOfObject is a method of NSArray.
Upvotes: 0
Reputation: 46020
You could use the menu items' representedObject
to store a reference to some object in your app. In your case, you would probably use the document that the menu item refers to:
[aMenuItem setRepresentedObject:yourDocument];
You could then access the object in the action like so:
- (void)myAction:(id)sender
{
NSMenuItem* mi = (NSMenuItem*)sender;
YourDocument* doc = (YourDocument*)[sender representedObject];
//do something with doc
}
Upvotes: 4