查看 NSTask 输出 Cocoa
See NSTask output Cocoa
我怎样才能做出类似这样的 if 语句:
if(the output of a nstask is equal to a specific string){
//do stuff over here
}
我是 运行 a NSTask
并且它在 NSLog 中输出了来自它的数据,但是我怎么能不在那里显示它而是将它存储为 NSString 或类似的东西那
这就是我的任务的样子
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/csrutil"];
[task setArguments:@[ @"status" ]];
[task launch];
非常感谢任何帮助:)
您需要 pipe
和 file 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" ]];
我怎样才能做出类似这样的 if 语句:
if(the output of a nstask is equal to a specific string){
//do stuff over here
}
我是 运行 a NSTask
并且它在 NSLog 中输出了来自它的数据,但是我怎么能不在那里显示它而是将它存储为 NSString 或类似的东西那
这就是我的任务的样子
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/csrutil"];
[task setArguments:@[ @"status" ]];
[task launch];
非常感谢任何帮助:)
您需要 pipe
和 file 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" ]];