【问题标题】:How do I have an NSTextField constantly update its value based on the output of a command line argument?如何让 NSTextField 根据命令行参数的输出不断更新其值?
【发布时间】:2012-10-01 12:58:42
【问题描述】:

我正在尝试在 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);

    }

    }

【问题讨论】:

  • 您希望它更新什么?使用进度指示器肯定更有意义吗?
  • 基本上 rsync 发生,并且在完成后输出出现在一个大批量字符串中。我想让字符串随着完成百分比等不断更新。 rsync 输出的
  • 听起来更像是rsync 的问题,而不是文本字段的问题。您是否尝试过将--progress 传递给rsync
  • 是的,我使用 --progress 并且它可以工作,除了 rsync 的整个输出被放入一个文件中并且它不会被不断地读取,只有在最后一次

标签: objective-c macos command-line nstask


【解决方案1】:

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

NSData *data = [file readDataToEndOfFile];

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 2013-10-03
    • 1970-01-01
    • 2013-02-07
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多