嗨:我想将标准输出重定向到 NSTextView。这也适用于子流程的输出吗?实现这一目标的最佳方法是什么?
编辑: 根据 Peter Hosey 的回答,我实现了以下内容。但我没有收到通知。我做错了什么?
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *pipeHandle = [pipe fileHandleForWriting];
dup2(STDOUT_FILENO, [pipeHandle fileDescriptor]);
NSFileHandle *fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:pipeHandle];
[fileHandle acceptConnectionInBackgroundAndNotify];
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self selector:@selector(handleNotification:) name:NSFileHandleConnectionAcceptedNotification object:fileHandle];
最佳答案
我想做同样的事情并发现了这篇文章。在阅读了这篇文章和苹果的文档后我才明白了这一点。我在这里包括我的解决方案。 “pipe”和“pipeReadHandle”在接口(interface)中声明。在 init 方法中我包含以下代码:
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] ;
handleNotification:方法是
[pipeReadHandle readInBackgroundAndNotify] ;
NSString *str = [[NSString alloc] initWithData: [[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] encoding: NSASCIIStringEncoding] ;
// Do whatever you want with str
关于cocoa - 在 Cocoa 中将 stdout 重定向到 NSTextView 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2406204/