cocoa - 带有多个参数的@selector

标签 cocoa macos nsmenu nsmenuitem

首先是我的代码:

   - (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");
}

我想将 item 作为参数提供给带有选择器的 press: 方法。

非常感谢:)

PS:我这样做是为了 Mac,而不是 iPhone。

最佳答案

NSMenuItem 有一个名为 setRepresentedObject: 的方法,菜单项对象将作为 sender 参数传递给 press: 方法。

因此,您需要调整代码以使用每个 NSMenuItem 附带的 item 调用 setRepresentedObject:,然后在 按:您可以调用[senderrepresentedObject]来取回该项目。

关于cocoa - 带有多个参数的@selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4698792/

相关文章:

ios - 如何在不改变顺序的情况下从plist加载数据

cocoa - 显示表格时可用的主菜单

objective-c - 验证菜单项 : not called

objective-c - 无法从文档 Controller 填充 NSMenu

iphone - 如何创建一个具有可由多个 ViewController 使用的关联 View 类的 Nib

iOS 将文档目录中我的应用程序保存的文件移动到另一台计算机

windows - OpenGL获取背景像素信息

python - Scapy模块: netif = rt[4 + mtu_present + prio_present + refs_present + locked] IndexError: list index out of range

ios - 您可以在不成为 Mac 管理员的情况下在 iOS 上创建和发布应用程序吗?

r - 在 macOS 上使用 RStudio 安装 RSymphony