我试图弄清楚如何将变量(在我的例子中为主机名)传递给我从以编程方式插入的“菜单项”创建的函数。
#function
-(void)goToTerminal:(NSString *)hostname {
NSString *s = [NSString stringWithFormat:@"tell application \"Terminal\" to do script \"ssh root@%@\"", hostname];
NSAppleScript *as = [[NSAppleScript alloc] initWithSource: s];
[as executeAndReturnError:nil];
}
# adding menu item in another function
[NSString *hostname = [NSString stringWithString:@"some.host"]];
NSMenuItem *subhostline = [[[NSMenuItem alloc] initWithTitle:sshtohost action:@selector(goToTerminal:) keyEquivalent:@""]autorelease];
[subhostline setTarget:self];
最佳答案
NSMenuItem 具有 -tag
和 -setTag:
方法,可用于将任意整数与菜单项关联。该整数很容易成为数组中主机名的索引。
目标/操作方法采用单个参数,即发送者。发送者是在目标上触发操作方法的 UI 元素。为了保持 MVC 固有的分离,通常不会将数据直接推送到 UI 元素中;而是将数据直接推送到 UI 元素中。 UI( View 层)对 Controller 执行操作,然后 Controller 从模型中选取适当的数据并执行其需要执行的任何操作。
关于objective-c - Cocoa Xcode - 如何将变量传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1916209/