从NSButton运行终端命令单击

时间:2013-09-06 16:21:33

标签: macos cocoa terminal nsbutton

我正在尝试使用Xcode构建一个基本的Mac OS应用程序,允许用户强制弹出卡在其驱动器中而不必每次都重新启动计算机。基本上我想在我的窗口上标记为“弹出”的NSButton,我正在寻找执行终端命令“drutil tray eject”的按钮,以便在没有响应时强行从驱动器中弹出CD。我是Xcode的新手,这是我的第一台Mac App。

谢谢! : - )

1 个答案:

答案 0 :(得分:0)

使用NSTask。请查看documentationQuartz Composer CommandLineTool

+ (void) executeShellCommandAsynchronously:(NSString*)command
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSTask *task = [[[NSTask alloc] init] autorelease];
    [task setLaunchPath: @"/bin/sh"]; //we are launching sh, it is wha will process command for us
    [task setStandardInput:[NSFileHandle fileHandleWithNullDevice]]; //stdin is directed to /dev/null
    NSArray *args = [NSArray arrayWithObjects:  @"-c", //-c tells sh to execute commands from the next argument
                     command, //sh will read and execute the commands in this string.
                     nil];
    [task setArguments: args];
    [task launch];
    [command release];
    [pool release];
    return;
}