4
votes

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?

1
What do you mean by "works much better"?Brian Donovan

1 Answers

9
votes

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