NSView’s -setNeedsDisplay: is not thread safe

One could assume such a trivial task like setting a BOOL (which is all that setNeedsDisplay does) would be thread safe. Well, it isn’t as I found out after a rather long debugging session. (With individual debug runs going up to 2 hours till the bug showed up).

If you get really unlucky and set the flag to true when the Cocoa drawing thread is doing its work the drawing thread will hang/crash. Event dispatch, your main thread, everything else will work – only your interface won’t get updated (your views’ -drawRect: methods won’t get called). A rather weird bug.

So call -setNeedsDisplay: only on the main thread. Luckily GCD makes that pretty straightforward:

dispatch_queue_t q = dispatch_get_main_queue();
dispatch_async(q, ^{
  [view setNeedsDisplay: YES];
});

Comments are closed.