Li Hongqiang principles and core mechanisms of iOS development Runloop

Source: Internet
Author: User

Li Hongqiang principles and core mechanisms of iOS development Runloop

After iOS has not been in-depth study of runloop, very ashamed. Just a while ago in charge of performance optimization projects, we need to use Runloop for performance optimization and performance testing, taking advantage of this opportunity to delve into the principles and characteristics of runloop.

definition of Runloop

When there is a continuous demand for asynchronous tasks, we create a separate life-cycle controllable thread. Runloop is the mechanism for controlling the thread life cycle and receiving events for processing.

Runloop is the most central mechanism for iOS incident response and task handling, which runs through the entire iOS system.

Foundation:nsrunloop
Core Foundation:cfrunloop, code Open source, C programming, cross-platform

Purpose

Power saving through runloop mechanism, smooth, fast response, good user experience

Understanding

Process is a factory, the thread is a pipeline, run loop is the head of the pipeline, when the factory received orders assigned to this assembly line, run loop to start the assembly line, let the assembly line moving, production products; When the product is finished, the run loop will temporarily stop the assembly line, Conserve resources.
Runloop Management pipeline, assembly line will not be destroyed by the factory idle, and do not need the assembly line, will be dismissed Runloop this supervisor, that is, the exit process, the release of all resources.

Runloop is not the exclusive concept of the iOS platform, in the multi-threaded programming of any platform, in order to control the life cycle of the thread, receive processing asynchronous messages need a similar runloop loop mechanism implementation, Android Looper is similar mechanism.

features
    • The runloop of the main thread is automatically created when the app is launched
    • Other threads need to start themselves under that thread
    • You cannot create runloop yourself
    • Runloop is not thread-safe, so you need to avoid invoking the current thread's runloop on other threads
    • Runloop is responsible for managing autorelease pools
    • Runloop is responsible for handling message events, i.e. input source events and timer events
runloop mechanism

The main thread (threads with runloop) almost all functions are redeployed from one of the following six functions:

  • Cfrunloop_is_calling_out_to_an_observer_callback_function
    Cfrunloop is calling-Abserver callback function
    For external reporting of changes to the current state of Runloop, many mechanisms in the framework are triggered by runloopobserver, such as Caanimation

  • Cfrunloop_is_calling_out_to_a_block
    Cfrunloop is calling off to a block
    Message notifications, non-deferred perform, dispatch calls, block callbacks, KVO

  • Cfrunloop_is_servicing_the_main_dispatch_queue
    Cfrunloop is servicing the main Desipatch queue

  • Cfrunloop_is_calling_out_to_a_timer_callback_function
    Cfrunloop is calling off to a timer callback function
    Deferred perform, deferred dispatch call

  • Cfrunloop_is_calling_out_to_a_source0_perform_function
    Cfrunloop is calling off to a source 0 perform function
    Handle app internal events, the app is responsible for managing (triggering), such as Uievent, Cfsocket. Normal function call, system call

  • Cfrunloop_is_calling_out_to_a_source1_perform_function
    Cfrunloop is calling off to a source 1 perform function
    Managed by Runloop and kernel, Mach port drives, such as Cfmachport, Cfmessageport

  • Runloop Architecture

??

    • Runloop Run time

There are six main types of statuses:

    • Kcfrunloopentry--Entering the Runloop cycle
    • Kcfrunloopbeforetimers--Handle callback before timing call
    • Kcfrunloopbeforesources--handling of input sources events
    • Kcfrunloopbeforewaiting--Runloop call before sleep
    • Kcfrunloopafterwaiting--Runloop wake-up call
    • Kcfrunloopexit--Exit Runloop
Runloop Run-time Call stack
    • Main thread App Runtime

    • The relationship between Runloopobserver and Autorelease pool

UIKit Runloopobserver The Autorelease object generated in this Loop by Pop and Push on the autorelease Pool between two Sleep Runloop.

    • Runloop suspend and wake-up

Specify the mach_port port for Wake-up
Call the mach_msg listener wake-up port, the system kernel hangs the thread before it wakes up, and stays in the mach_msg_trap state.
After the msg of this port is sent to the kernel by another thread, the trap state is awakened and Runloop continues to work.

Runloop Supported message events (events)
    • Runloop

    • Support for receiving processing input source events, including:

      The Mach port event of the system is a communication event
      Custom Input Events

    • Support for accepting processing timing source (timer) events

    • Before starting Runloop, you must add a listener input source event or timing source event, otherwise the call [Runloop Run] will return directly without going into the loop to keep the thread in the long-standing.

      If no input source event or timer event is added, the thread will always be in an infinite loop idling, occupying CPU time slices and not achieving a reasonable allocation of resources.
      Threads that do not have a while loop and do not add any input source or timer are directly completed and reclaimed by the system.

Error procedureNsrunloop *runloop = [nsrunloop Currentrunloop]; while (! Self.iscancelled &&! self.isfinished) {[Runloop rununtildate:[NSDate Datewithtimeintervalsincenow:3];}; //correct practice nsrunloop *runloop = [ Nsrunloop Currentrunloop]; [Runloop addport:[nsmachport Port] formode: Nsdefaultrunloopmode]; while (! Self.iscancelled &&! self.isfinished) { @autoreleasepool {[Runloop rununtildate:[ nsdate datewithtimeintervalsincenow:3]]; }} 
Run Loop Modes
  • Understand
    Run Loop mode is the type of product that is supported on the production line, and the pipeline can only run in one mode at a time, producing a certain type of product. A message event is an order.

  • Cocoa defines the four-medium mode

    Default:nsdefaultrunloopmode, default mode, when run loop does not specify mode, it runs in default mode
    Connection:nsconnectionreplymode, used to listen for events that handle network request Nsconnection
    Modal:nsmodalpanelrunloopmode,os x Modal Panel Event
    Event Tracking:uitrackingrunloopmode, dragging events
    Common Mode:nsrunloopcommonmodes is a collection of patterns that, when bound to a collection of events, is the equivalent of binding to each pattern within the set.

  • Runloop can specify the mode of operation over a period of time through [acceptinputformode:beforedate:] and [runmode:beforedate:]. If not specified, Runloop defaults to run under Default (repeatedly calling Runmode:nsdefaultrunloopmode Befordate:)

  • Start a timer on the main thread, and then drag UITableView or Uiscrollview, and the timer does not execute. This is because, for a better user experience, the event tracking mode has the highest priority in the main thread. When the user drags the control, the main thread's run loop is run under event tracking mode, and the timer created is defaulted to default mode, so the system does not immediately execute the event received under default mode. Workaround:

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1.0                                                   target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; //或 [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];[timer fire];
Run Loop Application Practice

There are three main scenarios for the Run loop:

    • Maintain the life cycle of the thread so that the thread does not automatically exit and exit when Isfinished is yes.
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];while (!self.isCancelled && !self.isFinished) { @autoreleasepool { [runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]]; }}
    • Create a resident thread to perform some of the tasks that will persist. The thread's life cycle is the same as the app
@autoreleasepool {        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; [runLoop run];}
    • A thread that listens for some kind of event, or performs a certain task, for a certain amount of time
      The following code, in 30 minutes, every 30s execution ontimerfired:. This scenario typically occurs when I need to continuously update an item for a certain amount of time after the app starts.
@autoreleasepool {    NSRunLoop * runLoop = [NSRunLoop currentRunLoop];    NSTimer * udpateTimer = [NSTimer timerWithTimeInterval:30 target:self selector:@selector(onTimerFired:) userInfo:nil repeats:YES]; [runLoop addTimer:udpateTimer forMode:NSRunLoopCommonModes]; [runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:60*30]];}
    • Creation of Runloop in afnetworking
+ (void) Networkrequestthreadentrypoint: (ID) __unused Object {@autoreleasepool {[[Nsthread CurrentThread] SetName:@ "Afnetworking"];Nsrunloop *runloop = [Nsrunloop Currentrunloop];//here is mainly to listen to a port, the purpose is to make this Thread does not recycle [runloop addport:[nsdefaultrunloopmode]; [Runloop Run]; }}+ (nsthread *) networkrequestthread {static nsthread *_networkrequestthread = NIL; static dispatch_once_t oncepredicate; dispatch_once (&oncepredicate, ^{_networkrequestthread = [[ nsthread alloc] initwithtarget:self selector: @selector (networkrequestthreadentrypoint:) object:nil]; [_networkrequestthread start]; }); return _networkrequestthread;}          

Li Hongqiang The Runloop principle and core mechanism of iOS development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.