任何人都知道在执行 NSTask 时从 NSTask 获取通知。我正在使用 NSTask 解压缩一个 zip 文件,并且需要在 NSProgressBar 中显示解压缩数据的进度。我没有找到执行此类任务的任何想法。所以我在进度栏中显示值。需要帮助来完成这项任务。提前致谢。
2 回答
使用NSFileHandleReadCompletionNotification
,NSTaskDidTerminateNotification
通知。
task=[[NSTask alloc] init];
[task setLaunchPath:Path];
NSPipe *outputpipe=[[NSPipe alloc]init];
NSPipe *errorpipe=[[NSPipe alloc]init];
NSFileHandle *output,*error;
[task setArguments: arguments];
[task setStandardOutput:outputpipe];
[task setStandardError:errorpipe];
output=[outputpipe fileHandleForReading];
error=[errorpipe fileHandleForReading];
[task launch];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name: NSFileHandleReadCompletionNotification object:output];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedError:) name: NSFileHandleReadCompletionNotification object:error];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TaskCompletion:) name: NSTaskDidTerminateNotification object:task];
//[input writeData:[NSMutableData initWithString:@"test"]];
[output readInBackgroundAndNotify];
[error readInBackgroundAndNotify];
[task waitUntilExit];
[outputpipe release];
[errorpipe release];
[task release];
[pool release];
/* Called when there is some data in the output pipe */
-(void) receivedData:(NSNotification*) rec_not
{
NSData *dataOutput=[[rec_not userInfo] objectForKey:NSFileHandleNotificationDataItem];
[[rec_not object] readInBackgroundAndNotify];
[strfromdata release];
}
/* Called when there is some data in the error pipe */
-(void) receivedError:(NSNotification*) rec_not
{
NSData *dataOutput=[[rec_not userInfo] objectForKey:NSFileHandleNotificationDataItem];
if( !dataOutput)
NSLog(@">>>>>>>>>>>>>>Empty Data");
[[rec_not object] readInBackgroundAndNotify];
}
/* Called when the task is complete */
-(void) TaskCompletion :(NSNotification*) rec_not
{
}
为了显示进度,您需要找出两件事:
- 存档中有多少文件,或者解压缩完成后它们将占用多少字节
- 到目前为止你解压了多少文件或字节
您可以通过阅读 unzip 任务的输出找到这些内容。Parag Bafna 的回答是一个开始;在 中receivedData:
,您需要解析输出以确定刚刚发生的进度,然后将该进度添加到到目前为止的运行进度计数中(例如,++_filesUnzippedSoFar
)。
第一部分,找出工作的总规模,比较棘手。您基本上需要在运行 unzip 之前运行 unzip:第一个,带有-l
(小写 L),是列出存档的内容;二是解压。第一个,您读取输出以确定存档包含多少文件/字节;第二个,您读取输出以确定进度条前进到的值。
设置进度条的属性是容易的部分;那些字面意思是doubleValue
和maxValue
。找出你在工作中的位置是困难的部分,并且是非常特定于领域的——你需要阅读 unzip 的输出(两次,以不同的形式),了解它告诉你的内容,并将其转化为进度信息。
NSTask 中没有任何东西可以帮助您。NSTask 的部分开始和结束于standardOutput
属性。它不知道 zip 文件、档案、档案内容甚至进度,因为这些都不适用于大多数任务。这一切都特定于您的任务,这意味着您必须编写代码来完成它。