title: Best way to make NSRunLoop wait for a flag to be set?
body: <p>In the Apple documentation for <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRunLoop/run" rel="noreferrer">NSRunLoop</a> there is sample code demonstrating suspending execution while waiting for a flag to be set by something else.</p>
  
  <pre><code>BOOL shouldKeepRunning = YES;        // global
  NSRunLoop *theRL = [NSRunLoop currentRunLoop];
  while (shouldKeepRunning &amp;&amp; [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
  </code></pre>
  
  <p>I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a <code>NSLog</code> on the line after the flag is being set (in another method) and then a line after the <code>while()</code> there is a seemingly random wait between the two log statements of several seconds.</p>
  
  <p>The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds.</p>
  
  <p>I have worked around this issue with the following code but it does not seem right that the original code doesn't work.</p>
  
  <pre><code>NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
  while (webViewIsLoading &amp;&amp; [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil])
    loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
  </code></pre>
  
  <p>using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart.</p>
  
  <p>Anyone any ideas why the original code exhibits this behaviour?</p>