带有多个参数的@selector
首先是我的代码:
- (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 上。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSMenuItem 有一个名为
setRepresentedObject:
的方法,菜单项对象将作为sender
参数传递给press:
方法。因此,您需要调整代码以使用每个
NSMenuItem
附带的item
调用setRepresentedObject:
,然后在press:< /code> 您可以调用
[senderrepresentedObject]
来取回该项目。NSMenuItem has a method called
setRepresentedObject:
, and the menu item object will be passed as thesender
parameter topress:
method.So you need to adjust your code to call
setRepresentedObject:
with theitem
that goes with eachNSMenuItem
, and then inpress:
you can call[sender representedObject]
to get that item back.我几乎肯定
@selector(press:)
消息中包含的“sender”参数是NSMenuItem
。所以:
这应该记录发送者是所选的
NSMenuItem
。edit 误解了问题...
您希望在选择某个 menuItem 时检索
item
对象。这很容易。只需执行以下操作:然后在您的
press:
方法中...I'm almost positive that the "sender" parameter that is included with the
@selector(press:)
message is theNSMenuItem
.So:
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:Then in your
press:
method...