RunLoop series of articles

RunLoop (2) : Data structure RunLoop (3) : event loop mechanism RunLoop (4) : RunLoop and thread RunLoop (5) : RunLoop and NSTimer iOS – AutoRelease and @Autoreleasepool: RunLoop and @Autoreleasepool

The outline

RunLoop profile

  • Run a loop, a loop that does something (such as receiving messages, processing messages, sleeping, etc.) while the program is running.
  • RunLoopIs an object that manages events/messages through an internally maintained event loop;
  • RunLoopNot a simple onedo... whileLoop, which involves switching between user and kernel states.

Event loop

Event loop is the management of events/messages. Event loop can achieve:

  • Hibernate threads to avoid resource hogging when there are no messages to process. Switch from user mode to kernel mode and wait for messages.
  • When a message needs to be processed, the thread immediately wakes up and returns to user mode to process the message.
  • By calling themach_msg()Function to transfer control of the current thread to the kernel/user state.

The basic functions of RunLoop

  • To keep the program running:

Without RunLoop, the program will exit as soon as main() completes. The reason our iOS application keeps running is that UIApplicationMain is called inside main(), which starts the main thread RunLoop inside;

  • Handle various events in App (such as touch events, timer events, etc.);
  • Save CPU resources, improve program performance: work when you should work, rest when you should rest.

RunLoop application category

  • Timer, PerformSelector
  • GCD:dispatch_async(dispatch_get_main_queue(), ^{ });
  • Event response, gesture recognition, interface refresh
  • Network request
  • AutoreleasePool

RunLoop object

  • There are two sets of apis in iOS to access and useRunLoop:
    • (1) Foundation:NSRunLoop(isCFRunLoopRefProvides an object-oriented API)
    • (2) the Core Foundation:CFRunLoopRef
  • NSRunLoopandCFRunLoopRefrepresentsRunLoopobject
  • NSRunLoopNot open source, whileCFRunLoopRefIs open source:The Core Foundation of source code
  • To obtainRunLoopObject mode:
    // Foundation
    [NSRunLoop mainRunLoop];     // Get the main thread RunLoop object
    [NSRunLoop currentRunLoop];  // Get the RunLoop object for the current thread
    // Core Foundation
    CFRunLoopGetMain(a);// Get the main thread RunLoop object
    CFRunLoopGetCurrent(a);// Get the RunLoop object for the current thread
Copy the code

Application of RunLoop in real development

  • Communicate with other threads using ports or custom input sources
  • Use timers on child threads
  • To solveNSTimerThe problem of stopping working while sliding
  • Control the life cycle of a thread and implement a resident thread
  • Use any in Cocoa applicationsperformSelector...methods
  • Monitoring application lag
  • Performance optimization
  • .

A link to the

Core Foundation source RunLoop