Best way to make NSRunLoop wait for a flag to be set?

Runloops can be a bit of a magic box where stuff just happens.

Basically you’re telling the runloop to go process some events and then return. OR return if it doesn’t process any events before the timeout is hit.

With 0.1 second timeout, you’re htting the timeout more often than not. The runloop fires, doesn’t process any events and returns in 0.1 of second. Occasionally it’ll get a chance to process an event.

With your distantFuture timeout, the runloop will wait foreever until it processes an event. So when it returns to you, it has just processed an event of some kind.

A short timeout value will consume considerably more CPU than the infinite timeout but there are good reasons for using a short timeout, for example if you want to terminate the process/thread the runloop is running in. You’ll probably want the runloop to notice that a flag has changed and that it needs to bail out ASAP.

You might want to play around with runloop observers so you can see exactly what the runloop is doing.

See this Apple doc for more information.

Leave a Comment