如何从一个线程使用NSTextView作为日志控制台?

Ron*_*nto 2 cocoa nstextview

我正在运行另一个处理线程,我想将结果记录到NSTextView,当发布新行时,它会更新视图并将滚动条定位到底部.有什么建议?

- (void)runProc
{
    do {
        [NSThread sleepForTimeInterval:0.1];
        [self reportInfo:@"tick"];
    } while (stop == NO);    
}

- (void)report:(NSString*)string;
{
    [[consoleView textStorage] beginEditing];
    [[[consoleView textStorage] mutableString] appendString:string];
    [[[consoleView textStorage] mutableString] appendString:@"\n"];
    [[consoleView textStorage] endEditing];

    NSRange range;
    range = NSMakeRange ([[consoleView string] length], 0);

    [consoleView scrollRangeToVisible: range];
}
Run Code Online (Sandbox Code Playgroud)

它得到大约50个条目然后锁定整个事情.

Rob*_*ger 5

大多数AppKit都不是线程安全的,您无法NSTextView从辅助线程更新.所有UI更新必须在主线程上完成.

您需要像这样调用您的报告方法:

[self performSelectorOnMainThread:@selector(report:) withObject:@"tick" waitUntilDone:YES];
Run Code Online (Sandbox Code Playgroud)