如何让 NSTextField 根据命令行参数的输出不断更新其值



我正在尝试在Cbjective-C中创建一个小的rsync程序。它目前通过 NSTask 访问终端命令行,并将命令行的输出读取到 NSTextField 中显示的字符串中;但是,当我在非常大的文件(大约 8 GB)上使用此小程序时,它直到 RSYNC 完成后才会显示输出。我希望 NSTextField 在进程运行时不断更新。我有以下代码,正在寻找想法!

 -(IBAction)sync:(id)sender
{
    NSString *sourcePath = self.source.stringValue;
    NSString *destinationPath = self.destination.stringValue;
    NSLog(@"The source is %@. The destination is %@.", sourcePath, destinationPath);
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath:@"/usr/bin/rsync"];
    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-rptWav", @"--progress", sourcePath, destinationPath, nil];
    [task setArguments: arguments];
    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
       // [task setStandardInput:[NSPipe pipe]];
    NSFileHandle *file;
    file = [pipe fileHandleForReading];
    [task launch];
    NSData *data;
    data = [file readDataToEndOfFile];
    while ([task isRunning])
    {
        NSString *readString;
        readString = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];
        textView.string = readString;
        NSLog(@"grep returned:n%@", readString);
    }
    }

好的,问题在于您从管道读取数据的方式。 您正在使用:

NSData *data = [file readDataToEndOfFile];

它将一次性读取子进程写入的所有内容,直到管道关闭(当子进程终止时)。

您需要做的是一次读取一个字符并重建输出行。 您还希望使用非阻塞模式,以便在没有要读取的数据时主 UI 线程不会中断(更好的是,这应该在后台线程中完成,以便主 UI 线程保持完全不间断)。

最新更新