我想解析我使用NSTask執行的shell命令的輸出。尋找一個特定的子字符串就足夠了,只有子字符串永遠找不到。rangeOfString和編碼
我迄今爲止代碼:
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
NSLog(string);
if([string rangeOfString:@"Connection refused"].location != NSNotFound) {
NSLog(@"found");
} else {
NSLog(@"not found");
}
它始終打印「未找到」即使字符串搜索包含在可變串。提前致謝。
不幸的是,它不是那麼容易。當我像我這樣初始化我正在搜索的字符串時,rangeOfString按預期工作(即使在非反轉條件下)。將執行命令的輸出轉換爲NSString(可能是編碼或其他?)。 – devrandom