Question

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.

Was it helpful?

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.

OTHER TIPS

I'm almost positive that the "sender" parameter that is included with the @selector(press:) message is the NSMenuItem.

So:

- (void) press:(id)sender {
  NSLog(@"sender: %@", sender);
}

That should log that the sender is the NSMenuItem that was selected.

edit misinterpreted the question...

You want to retrieve the item object when a certain menuItem is selected. That's easy. Just do:

NSMenuItem * menuItem = [m addItemWithTitle:[item title] action:@selector(press:) keyEquivalent:@""];
[menuItem setTarget:self];
[menuItem setRepresentedObject:item];

Then in your press: method...

- (void) press:(id)sender {
  //sender is the NSMenuItem
  id selectedItem = [sender representedObject];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top