4

I have recently found that when waiting for my NSURLConnections to come through it works much better if I tell the waiting thread to do:

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

instead of

[NSThread sleepForTimeInterval:1];

After reading a bit about NSRunLoop runMode:beforeDate: it sounds like it is preferable over sleep just about always. Have people found this to be true?

TurqMage
  • 3,321
  • 2
  • 31
  • 52

1 Answers1

9

Yes, NSRunLoop is better because it allows the runloop to respond to events while you wait. If you just sleep your thread your app will block even if events arrive (like the network responses you are waiting for).

I usually have this construction:

while ([self isFinished] == NO) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

And then have isFinished return true when you want to stop blocking. Eith

mlaster
  • 417
  • 3
  • 5
  • 1
    Running the runloop in a public mode re-entrantly can often lead to unexpected consequences. For example, schedule a repeating timer for 1 second. The timer fires, calls a method that does this, this fires the timer again while it is still firing, and now you've called your timer handler re-entrantly. – Jon Hess Nov 01 '12 at 00:48