2

我正在尝试解析我使用 NSTask 执行的 shell 命令的输出。寻找特定的子字符串就足够了,只有永远找不到子字符串。

到目前为止我的代码:

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");
}

即使搜索的子字符串包含在变量string中,它也总是打印“未找到” 。提前致谢。

4

2 回答 2

0

我错了。该命令的输出实际上是空的(因此显然没有找到要查找的字符串)。我期望 NSLog 调用的结果实际上是命令直接输出到控制台(stderr?)。对此感到抱歉:(。

于 2012-11-01T15:35:13.457 回答
0

我很惊讶,但是当我把条件写反时。有效。请检查以下示例:

NSString *string = @"hello bla Connection refused Connection refused bla";
if ([string rangeOfString:@"Connection refused"].location == NSNotFound) {
    NSLog(@"string does not contain Connection refused");
} else {
    NSLog(@"string contains Connection refused!");
}

希望我清楚..

于 2012-11-01T12:34:21.410 回答