将标准输出重定向到 Cocoa 中的 NSTextView 的最佳方法是什么? [英] What is the best way to redirect stdout to NSTextView in Cocoa?

查看:18
本文介绍了将标准输出重定向到 Cocoa 中的 NSTextView 的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨:我想将标准输出重定向到 NSTextView.这也适用于子流程的输出吗?实现这一目标的最佳方法是什么?

Hi: I want to redirect stdout to a NSTextView. Could this also work with outputs of subprocesses? What might be the best way to achieve this?

根据 Peter Hosey 的回答,我实施了以下操作.但我没有收到通知.我做错了什么?

According to Peter Hosey answer I implemented the following. But I do not get a notification. What am I doing wrong?

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];

推荐答案

我也想做同样的事情,结果发现了这篇文章.在阅读了这个和 Apple 的文档后,我能够弄清楚.我在这里包括我的解决方案.在接口中声明了pipe"和pipeReadHandle".在 init 方法中,我包含了以下代码:

I was looking to do the same thing and came across this post. I was able to figure it out after reading this and Apple's documentation. I'm including my solution here. "pipe" and "pipeReadHandle" are declared in the interface. In the init method I included the following code:

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: 方法是

The handleNotification: method is

[pipeReadHandle readInBackgroundAndNotify] ;
NSString *str = [[NSString alloc] initWithData: [[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] encoding: NSASCIIStringEncoding] ;
// Do whatever you want with str 

这篇关于将标准输出重定向到 Cocoa 中的 NSTextView 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆