【问题标题】:See NSTask output Cocoa见 NSTask 输出 Cocoa
【发布时间】:2016-08-25 14:47:30
【问题描述】:

我怎样才能做出这样的 if 语句:

if(the output of a nstask is equal to a specific string){
   //do stuff over here
}

我正在运行NSTask,它会将来自它的数据放在 NSLog 中,但我怎么能不在那里显示它,而是将它存储为 NSString 或类似的东西

这就是我的任务的样子

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/csrutil"];
[task setArguments:@[ @"status" ]];
[task launch];

非常感谢任何帮助:)

【问题讨论】:

    标签: objective-c cocoa nstask


    【解决方案1】:

    您需要pipefile handle 才能读取结果。

    写一个方法

    - (NSString *)runShellScript:(NSString *)cmd withArguments:(NSArray *)args
    {
        NSTask *task = [[NSTask alloc] init];
        [task setLaunchPath:cmd];
        [task setArguments:args];
    
        NSPipe *pipe = [NSPipe pipe];
        [task setStandardOutput: pipe];
        NSFileHandle *file = [pipe fileHandleForReading];
    
        [task launch];
    
        NSData *data = [file readDataToEndOfFile];
        return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    }
    

    然后调用它

    NSString *result = [self runShellScript:@"/usr/bin/csrutil" withArguments:@[ @"status" ]];
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 2023-03-16
    • 2013-05-30
    • 2012-08-17
    • 2013-08-01
    相关资源
    最近更新 更多