Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Sleep and NSRunLoop runMode:beforeDate:

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?

like image 496
TurqMage Avatar asked Jan 18 '23 11:01

TurqMage


1 Answers

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

like image 101
mlaster Avatar answered Jan 21 '23 00:01

mlaster