iOS NSRunLoop in a nutshell

What is a NSRunLoop?

A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.

That’s what docs say. Each thread, including the application’s main thread, has an associated NSRunLoop object. The app frameworks automatically set up and run the run loop on the main thread as part of the application startup process.

A NSRunLoop object processes input for sources such as mouse and keyboard events from the window system, NSPort objects, and NSConnection objects. A NSRunLoop object also processes NSTimer events. Input sources deliver asynchronous events, usually messages from another thread. Timer sources deliver scheduled events, that are either repeated or delivered at a particular time.

NSRunLoop

A NSRunLoop object delivers the events to the thread, events that can be handled by the thread. Thus the code you write will handle these events.

In a big simplification you can think of a run loop like of a while loop:

while(1) {
    checkInputSourcesAndInformThreadIfNeeded();
}

But a NSRunLoop does not only that. It can also schedule methods for execution and prioritize them (e.g. performSelector:target:argument:order:modes: method). Moreover, it can generate notifications about its behavior. Other objects can register as observers to get notified about run loop events.

To find more about run loops, check out Threading Programming Guide.

Related