如何拥有具有动态操作的 NSMenu

发布于 2024-08-04 07:50:34 字数 203 浏览 5 评论 0原文

我想创建一个 NSMenu,其选项类似于您在 Windows 资源管理器中找到的“发送到”选项,其中它将列出您可以将文件发送到的附加设备。

根据我的研究,似乎不可能定义一个向函数发送参数的选择器,因此这不是使用 @selector(@"sendToVolume:1") 的情况。那么,当项目数量未知时,我还能如何让菜单根据单击的项目执行不同的任务呢?

I want to create an NSMenu with an option similar to the Send To option you'd find in Windows Explorer where it will list the devices attached that you can send the file to.

From my research it seems that it's not possible to define a selector that sends a parameter to the function as well, so it's not a case of having @selector(@"sendToVolume:1"). So how else could I have the menu perform a different task based on which item is clicked when the number of items is unknown?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

素衣风尘叹 2024-08-11 07:50:34

NSMenuItem 有一个representedObject 属性,可用于存储您想要的任何内容,例如对项目所代表的目的地的引用。

当选择器被调用时,您可以获取representedObject:

-(IBAction)sendTo:(id)sender {
    id destination = [sender representedObject];
}

NSMenuItem has a representedObject property, which can be used to store anything you'd like, such as a reference to the destination that item represents.

When the selector is invoked, you can then get the representedObject back:

-(IBAction)sendTo:(id)sender {
    id destination = [sender representedObject];
}
万劫不复 2024-08-11 07:50:34

但您可以使用带参数的选择器! NSObject 定义了三个方法,如下所示:

-performSelector:
-performSelector:withObject:
-performSelector:withObject:withObject:

现在,第一个就像有 @selector(someMethod:) ,但最后两个用于向选择器发送参数。例如:

-(void)sendToVolume:(NSNumber)nr { 
//do stuff
}

那么你可以这样使用它:

[appController performSelector:@selector(sendToVolume:) 
               withObject:[NSNumber numberWithInt:1]];

But you can use selectors with parameters! NSObject has three methods defined like this:

-performSelector:
-performSelector:withObject:
-performSelector:withObject:withObject:

Now, the first is like having @selector(someMethod:), but the last two are used to send parameters to the selector. For example:

-(void)sendToVolume:(NSNumber)nr { 
//do stuff
}

then you could use it like this:

[appController performSelector:@selector(sendToVolume:) 
               withObject:[NSNumber numberWithInt:1]];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文