Search code examples
cocoamacosnsmenunsmenuitem

@selector with multiple arguments


first my code:

   - (NSMenu*)sourceList:(PXSourceList*)aSourceList menuForEvent:(NSEvent*)theEvent item:(id)item
    {
     if ([theEvent type] == NSRightMouseDown || ([theEvent type] == NSLeftMouseDown && ([theEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask)) {
      NSMenu * m = [[NSMenu alloc] init];  
      if (item != nil) {
       NSLog(@"%@",[item title]);

       [m addItemWithTitle:[item title] action:@selector(press:) keyEquivalent:@""]; // problem. i want to give "item" as an argument.....

       for (NSMenuItem* i in [m itemArray]) {
        [i setTarget:self];
       }
      } else {
       [m addItemWithTitle:@"clicked outside" action:nil keyEquivalent:@""];
      }
      return [m autorelease];
     }
     return nil;
    }
-(void) press:(id)sender{
 NSLog(@"PRESS");
}

I want to give item as an argument to my press: method with a selector.

Thank you very much :)

PS: I'm doing this for the mac not iPhone.


Solution

  • NSMenuItem has a method called setRepresentedObject:, and the menu item object will be passed as the sender parameter to press: method.

    So you need to adjust your code to call setRepresentedObject: with the item that goes with each NSMenuItem, and then in press: you can call [sender representedObject] to get that item back.