【发布时间】:2019-12-13 06:07:16
【问题描述】:
我尝试使用 NSTask 列出 Director 中的文件/文件夹,如何将每行的输出放入列表中?我尝试打印出来,它只显示第一行。
NSTask * list = [[NSTask alloc] init];
[list setLaunchPath:@"/bin/ls"];
[list setCurrentDirectoryPath:@"/"];
NSPipe * out = [NSPipe pipe];
[list setStandardOutput:out];
[list launch];
[list waitUntilExit];
NSFileHandle * read = [out fileHandleForReading];
NSData * dataRead = [read readDataToEndOfFile];
NSString * stringRead = [[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding]];
HBLogDebug(@"PATH: %@", stringRead); //Only the first line printed
NSMutableArray *outputlist = [[NSMutableArray alloc] init];
//This part here I'm not so sure how to proceed since it's only one line, I expected multiples line
for (NSString *s in stringRead?dataRead?){
[outputlist addObject:s];
}
提前致谢!
【问题讨论】:
-
你
waitUntilExit在使用fileHandleForReading获得输入之前,也许只是放弃前者,这样你的进程在你尝试获得它的输出之前还没有死掉?也就是说,对于这个特定任务,您最好使用NSFileManagerdocumentation 的 Discovery Directory Contents 部分中的一种方法。 HTH -
删除
waitUntilExit将冻结运行此代码的系统/UI,不幸的是。关于NSFileManager,这将起作用,但仅出于此目的,上面的代码只是一个示例(ls) -
如前所述,您可以使用 NSFileHandle 的
readToEndOfFileInBackgroundAndNotify在后台运行任务并发出通知。从那里只需在行终止符(\n 和/或 \r)处分解结果字符串,使用 NSString 的componentsSeparatedByString或componentsSeparatedByCharactersInSet将其放入数组中。 -
@GregorIsack - 删除
waitUntilExit不应该冻结你的 UI,如果有的话它可能会产生相反的效果 - 在同步读取之前等待 可能会导致挂起。我添加了一些工作代码作为答案,它可以帮助您找出导致冻结的代码的不同之处。 HTH
标签: objective-c