Is there any guide for iOS runloop mechanism?

CarmeloS picture CarmeloS · Jun 2, 2011 · Viewed 16.1k times · Source

I'm learning socket communication on iPhone, and its guide said something about CFRunloop(it is a guide for CFNetwork, can this be used on iOS?) Where can I learn about runloop on iOS?API reference is not enough.

Answer

Jeremy W. Sherman picture Jeremy W. Sherman · Jun 2, 2011

Look at the "Run Loops" chapter of Apple's Threading Programming Guide. In brief:

  • There is one run loop associated with each thread.
  • The run loop has to be run to do anything. Apple's application main function takes care of this for you on the main thread.
  • A run loop is run in a specific mode. The "common mode" is actually a set of modes, and there is an API for adding modes to that set.
  • A run loop's main purpose is to monitor timers and run loop sources. Each source is registered with a specific run loop for a specific mode, and will only be checked at the appropriate time when the runloop is running in that mode.
  • The run loop goes through several stages in each go around its loop, such as checking timers and checking other event sources. If it finds that any source is ready to fire, it triggers the appropriate callback.
  • Aside from using ready-made run loop tools, you can create your own run loop sources as well as registering a run loop observer to track the progress of the run loop.

One major pitfall is forgetting to run the run loop while waiting for a callback from a runloop source. This is sometimes a problem when you decide to busy-wait for something to happen on the main thread, but you're most likely to run into it when you create your own thread and register a runloop source with that runloop. You are responsible for establishing an autorelease pool and running the runloop if needed on non-main threads, since the application main function will not be there to do it for you.

You would do better to read Apple's Concurrency Programming Guide instead, which suggests alternatives to the runloop mechanism such as operation queues and dispatch sources. The "Replacing Run-Loop Code" section of the "Migrating Away from Threads" chapter suggests using dispatch sources instead of runloop sources to handle events.