objective-c - 如何将 STDOUT 重定向到 NSTextView?

标签 objective-c macos cocoa stdout

有人可以告诉我如何将 Stdout 重定向到 NSTextView 吗?

NSLog打印的信息是否属于std?

谢谢

最佳答案

下面的代码使用 dup2 将标准输出插入到 NSPipe 对象的写入端。使用 GCD 调度源观察读取端,它从管道读取数据并将其附加到 TextView 。

NSPipe* pipe = [NSPipe pipe];
NSFileHandle* pipeReadHandle = [pipe fileHandleForReading];
dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stdout));
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, [pipeReadHandle fileDescriptor], 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_event_handler(source, ^{
    void* data = malloc(4096);
    ssize_t readResult = 0;
    do
    {
        errno = 0;
        readResult = read([pipeReadHandle fileDescriptor], data, 4096);
    } while (readResult == -1 && errno == EINTR);
    if (readResult > 0)
    {
        //AppKit UI should only be updated from the main thread
        dispatch_async(dispatch_get_main_queue(),^{
            NSString* stdOutString = [[NSString alloc] initWithBytesNoCopy:data length:readResult encoding:NSUTF8StringEncoding freeWhenDone:YES];
            NSAttributedString* stdOutAttributedString = [[NSAttributedString alloc] initWithString:stdOutString];
            [self.logView.textStorage appendAttributedString:stdOutAttributedString];
        });
    }
    else{free(data);}
});
dispatch_resume(source);

NSLog(@"...") 虽然不会输出到 stdout - 它会打印到 stderr。如果您想将其重定向到您的 TextView ,请更改

dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stdout));

dup2([[pipe fileHandleForWriting] fileDescriptor], fileno(stderr));

关于objective-c - 如何将 STDOUT 重定向到 NSTextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16391279/

相关文章:

iPhone开发

c - 当我试图编译它时,Xcode 关闭项目

cocoa - 使用 dataWithPDFInsideRect 保存数据 : just makes a black pdf

macos - 拉伸(stretch) NSImage 以制作类似 iMessage 的气泡

iphone - 如何在iPhone中点击外部时隐藏下拉列表

ios - 为什么,将 nil 作为参数从 Objc C 发送到 swift 类初始值设定项,用新对象替换 nil 参数

objective-c - LSSharedFileListItemResolve 抛出 : "URLs with the type "nwnode :"are not supported"

xcode - 防止选择时更改 NSPopUpButton 的标题

ios - UIScrollView 不使用自动布局滚动(内容 View 框架大小以编程方式更改)

ios - Objective-C : Webviewcontroller is reloading after opening photo gallery