2016-08-25 40 views
0

我怎麼可能做出的聲明,如果是這樣的:見NSTask輸出可可

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]; 

任何幫助是極大的讚賞:)

東西

回答

3

您需要一個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" ]]; 
+0

感謝您的幫助,但我怎麼可能讓一個if if語句的結果等於一個字符串? – Bisquitue

+0

[如何檢查NSString是否等於一個特定的字符串值?](http://stackoverflow.com/q/7266218)@Bisquitue –

+0

@JoshCaswell這是一個愚蠢的問題,我剛發現它後我才意識到它 – Bisquitue