The Apple documentation says that the sender passed to the NSMenuItem's action can be set to some custom object, but I can't seem to figure out how to do this. Is there a method I'm not seeing someplace in the documentation?
Asked
Active
Viewed 6,871 times
1 Answers
30
I'm not sure what piece of documentation you're referring to (a link would help).
You can use the -setRepresentedObject:
method of NSMenuItem
to associate an arbitrary object with a menu item:
//assume "item" is an NSMenuItem object:
NSString* someObj = @"Some Arbitrary Object";
[item setRepresentedObject:someObj];
[item setAction:@selector(doSomething:)];
Then when the menu item sends its action message you can obtain the object:
- (IBAction)doSomething:(id)sender
{
NSLog(@"The menu item's object is %@",[sender representedObject]);
}

Rob Keniger
- 45,830
- 6
- 101
- 134
-
I can't remember off the top of my head what documentation it was, but I did end up figuring this out. – Jeff Barger May 13 '10 at 19:26
-
Silly question : Why use the representedObject when we can just use the NSMenuItem title ? – Bertrand Caron Oct 21 '13 at 16:16
-
7You shouldn't use titles because they can be localized etc. It's much better to use the `-representedObject` as it's designed to store arbitrary data. – Rob Keniger Oct 22 '13 at 03:49