Question

From this Apple documentation:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1 ,

Run loops are part of the fundamental infrastructure associated with threads. A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events

When we use Cocoa APIs, does all of the code run in a runloop?

Was it helpful?

Solution

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

The answer to your question is YES and NO. It is a matter of interpretation.

An NSRunLoop object processes input for sources such as mouse and keyboard events from the window system, NSPort objects, and NSConnection objects. An NSRunLoop object also processes NSTimer events.

A run loop delivers the events to the thread, events that can be handled by the thread. Thus the code you write will handle these 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.

enter image description here

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

while(1)
{
    checkInputSourcesAndInformThreadIfNeeded();
}

But a run loop does not only that. It can also schedule methods for execution and prioritize them (see 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.

Based on Threading Programming Guide and NSRunLoop Class Reference.

Related SO thread: How to implement an NSRunLoop inside an NSOperation

OTHER TIPS

main doesn't. Code in worker threads doesn't. Signal handlers may or may not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top