Question

I have an NSTextView that I'm making function as a console. To log stuff, I use the following method:

- (void)log:(NSString *)logString
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* dateTime = [formatter stringFromDate:[NSDate date]];

    [[self consoleText] setString:[NSString stringWithFormat:@"%@\n[%@]: %@", [self consoleText].string, dateTime, logString]];

}

This method works great until the log window gets full. As soon as the scrollbar appears, the log function causes the program to hang. Why?

Edit:

I added some logging and found out that the exact line that is causing the program to hang is:

[[self consoleText] setString:[NSString stringWithFormat:@"%@\n[%@]: %@", [self consoleText].string, dateTime, logString]];

The particular problem is arising from the setString: method in it of itself. If I separate the stringWithFormat: and declare the string to set it to beforehand, it still hangs at:

[[self consoleText] setString:outputString];

but only when the content is large enough to incur a scrollbar.

Was it helpful?

Solution

The true issue here was that this method was called from a background thread. AppKit is not safe in the background thread, so you should to call all UI updates from the main thread. Placing the setString: in a main queue asynchronous dispatch fixed the issue:

dispatch_async(dispatch_get_main_queue(), ^(void){
    [[self consoleText] setString:outputString];
});

Very odd that it worked fine until a scrollbar needed to appear...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top