我在这个问题中遵循了选定的答案帖子:
在 Cocoa 中将标准输出重定向到 NSTextView 的最佳方法是什么?
跟着我感觉有点熟悉。我为管道和读取处理程序创建了一个 NSPipe 和 NSFileHandler 对象,并使用了通知。由于我的需要,我将下面的 open 方法放在 viewDidAppear 和 viewDidDisappear 方法中,但是您可以将其放在合适的位置
// Piping stdout info from here WILL NOT PIPE NSLOG:
// https://stackoverflow.com/questions/2406204/what-is-the-best-way-to-redirect-stdout-to-nstextview-in-cocoa
- (void) openConsolePipe {
_pipe = [NSPipe pipe];
_pipeReadHandle = [_pipe fileHandleForReading] ;
dup2([[_pipe fileHandleForWriting] fileDescriptor], fileno(stdout)) ;
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleNotification:) name: NSFileHandleReadCompletionNotification object: _pipeReadHandle] ;
[_pipeReadHandle readInBackgroundAndNotify] ;
}
- (void) closeConsolePipe {
if (_pipe != nil) {
[[_pipe fileHandleForWriting] closeFile];
// documentation suggests don't need to close reading file handle b/c auto but this suggests otherwise:
// https://stackoverflow.com/questions/13747232/using-nstask-and-nspipe-causes-100-cpu-usage
// [[_pipe fileHandleForReading] closeFile];
}
}
- (void) handleNotification:(NSNotification *)notification {
[_pipeReadHandle readInBackgroundAndNotify] ;
NSString *str = [[NSString alloc] initWithData: [[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] encoding: NSUTF8StringEncoding];
// do what you want with the str here.
[_consoleView setText:[_consoleView.text stringByAppendingString:str]];
[_consoleView scrollRangeToVisible:NSMakeRange([_consoleView.text length], 0)];
}
我希望这最终能帮助其他人在谷歌上搜索这个......