Objective-C 如何将 NSTask 输出定向到 NSTextField

How to direct NSTask output to NSTextField in Objective-C

所以目前我正在做一个小的个人项目,它在资源包中运行一个 bash 脚本,我可以让它正确地将控制台日志输出到 NSLog,但是字符串不会重写一个 NSTextField 或重绘一个 NSTextView

- (IBAction)doIt:(NSButton *)sender
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments;
    NSString* newpath = [[NSBundle mainBundle] pathForResource:@"run" ofType:@"sh"];
    NSLog(@"shell script path: %@",newpath);
    arguments = [NSArray arrayWithObjects:newpath, nil];
    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    NSPipe *input = [NSPipe pipe];
    [task setStandardOutput: pipe];
    [task setStandardInput: input];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];
    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];


    NSLog (@"script returned:\n%@", string);
}

所以末尾的字符串将使用 NSLog 正确输出,但这就是我所能做的...有什么想法吗?

您需要在 XIB 文件中或以编程方式在您的代码中创建 NSTextFieldNSTextView

如果您想在 XIB 文件中创建它,请按照以下步骤(对于 ARC)进行操作:

1) 将 IBOutlet 属性 添加到控制器中的 .h 文件(例如 AppDelegate):

@property (nonatomic, weak) NSTextField *textField;

@property (nonatomic, assign) NSTextView *textView;

2) 转到您的 XIB 文件,创建一个新的 NSTextFieldNSTextView 并将其放在 window 上。右键单击您的控制器 class 并将连接拖到您的 NSTextFieldNSTextView.

3) 现在 IBOutlet 已连接到 XIB 中的视图,您需要做的就是通过调用

在 .m 文件中设置字符串值
[self.textField setStringValue:[NSString stringWithFormat:@"script returned:\n%@", string]];

对于 NSTextField

[self.textView setString:[NSString stringWithFormat:@"script returned:\n%@", string]];

对于 NSTextView

希望对您有所帮助。