(Mac)创建执行shell脚本的Xcode应用程序

时间:2012-04-10 01:54:09

标签: objective-c xcode cocoa shell

我想要完成的事情似乎很简单,远远低于Xcode / Interface Builder的能力。我搜索并搜索过,但没有提出我的答案,但大多数搜索引导我到这里,所以我创建了一个帐户来询问专家。我想创建一个非常简单的GUI,它将有四到五个按钮,每个按钮执行一个简单的shell脚本,终端窗口将不是必需的,但我可以忍受一个启动,如果这是它的方式。除了shell脚本,我还需要在应用程序中使用adb(Android调试桥)和fastboot实用程序。我假设我需要在Resources文件夹中放置adb和fastboot以及我的其他文件,我还假设我需要将我的shell scrips放在Classes文件夹中。我真的只需要知道如何将按钮连接到脚本,我希望它只是一些我忽略的简单。提前谢谢。

MacBook Pro 7,1 OSX 10.6.8 Xcode 3.2.6

1 个答案:

答案 0 :(得分:8)

试试这个:

- (void)runCmd:(NSString *)cmd withArgs:(NSArray *)args
{
    if (task)
    {
        [task interrupt];

    }
    else
    {
        task = [[NSTask alloc] init];
        [task setLaunchPath:cmd];

        [task setArguments:args];

        [pipe release];

        pipe = [[NSPipe alloc] init];
        [task setStandardOutput:pipe];

        NSFileHandle* fh = [pipe fileHandleForReading];

        NSNotificationCenter* nc;

        nc = [NSNotificationCenter defaultCenter];
        [nc removeObserver:self];
        [nc addObserver:self 
               selector:@selector(dataReady:) 
                   name:NSFileHandleReadCompletionNotification 
                 object:fh];
        [nc addObserver:self selector:@selector(dataAvailable:) name:NSFileHandleDataAvailableNotification object:fh];
        [nc addObserver:self 
               selector:@selector(taskTerminated:) 
                   name:NSTaskDidTerminateNotification 
                 object:task];

        [task launch];
        [fh readInBackgroundAndNotify];
    }
}

- (void)dataAvailable:(NSNotification*)n
{
    NSLog(@"Data Available : %@",n);
}

- (void)dataReady:(NSNotification*)n
{
    NSData* d;

    d = [[n userInfo] valueForKey:NSFileHandleNotificationDataItem];

    if ([d length])
    {
        NSLog(@"Data Ready : %@",[[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding]);
        [[[task standardOutput] fileHandleForReading] readInBackgroundAndNotify];
    }
}

- (void) taskTerminated:(NSNotification*)note
{
    [task release];
    task = nil;
}