[英]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文件中或以編程方式在代碼中創建一個NSTextField
或NSTextView
。
如果要在XIB文件中創建它,請按以下步驟操作(對於ARC):
1)將IBOutlet
屬性添加到控制器中的.h文件中(例如AppDelegate):
@property (nonatomic, weak) NSTextField *textField;
要么
@property (nonatomic, assign) NSTextView *textView;
2)轉到您的XIB文件,創建一個新的NSTextField
或NSTextView
並將其放在窗口中。 右鍵單擊控制器類,然后將連接拖動到NSTextField
或NSTextView
。
3)現在, IBOutlet
已連接到XIB中的視圖,您所需要做的就是通過調用以下命令在.m文件中設置字符串值
[self.textField setStringValue:[NSString stringWithFormat:@"script returned:\n%@", string]];
為NSTextField
要么
[self.textView setString:[NSString stringWithFormat:@"script returned:\n%@", string]];
對於一個NSTextView
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.