Personal insights on Runloop in iOS development

Source: Internet
Author: User

It's been almost two years since I've been in touch with iOS, and there's a certain understanding of runloop in iOS, and here's a personal understanding of Runloop .

first knowledge of Runloop

Runloops is the basic part associated with the line threads, a run loop is the event-handling loop that is used to dispatch and coordinate the received event handling. The purpose of using Runloop is to make the thread have a job to do when it is busy, and when nothing is done, it can cause the thread to hibernate.

Our general procedure is to execute a thread, which is a straight line. There is a starting point. and Runloop is always on the thread above the circle, has been running laps, unless cut off otherwise have been running. The analogy on the internet is very good, the straight line is like a flash, the circle is like the OS, running until you shut down the computer.

Runloop Information

Apple official documents:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/ Runloopmanagement.html

Cfrunloopref is open-source:

http://opensource.apple.com/source/CF/CF-1151.16/

Runloop Object

iOS has two sets of APIs to access and use Runloop

    • Foundation Frame--Nsrunloop
    • Core Foundation Framework-->cfrunloopref

Nsrunloop and Cfrunloopref all represent Runloop objects.
Nsrunloop is a cfrunloopref-based OC Wrapper, so to understand the RUNLOOP internal structure, you need to study the CFRUNLOOPREF level of the API (Core Foundation layer)

Runloop and threading

    • Each thread has a unique Runloop object corresponding to it (if I want to open a sub-line and let the thread die, the child thread opens a runloop)
    • The runloop of the main thread has been automatically created, and the runloop of the child threads need to be actively created
    • Runloop created on first fetch, destroyed at end of thread

Get Runloop Object

    • Foundation
// gets the Runloop object for the current thread // get the Runloop object for the main thread
    • Core Foundation
// gets the Runloop object for the current thread // get the Runloop object for the main thread

If it is in the main thread: The Runloop object of the current threads and the Runloop object of the main course get the same.

Cfrunloopsourceref

    • Cfrunloopmoderef represents the operating mode of Runloop
    • One RunLoop contains several Mode , each of which Mode contains several Source / Timer /Observer
    • Each time the Runloop is started, only one mode can be specified, and this mode is called the CurrentMode (can be obtained [NSRunLoop currentRunLoop].currentMode )
    • If you need to switch mode, you can only exit the loop and reassign a mode entry (because Runloop is a running loop, always running, swapping another mode, you must first exit and then run in another mode)
    • This is done mainly to separate the different groups of Source / Timer / Observer , so that they do not affect each other (switching mode is to let it follow the other mode of the Source,timer,observer to run, do not affect each other)

Runloop boot must pass in a pattern, Runloop has multiple modes, but only one mode can be run at a time

Runloop defines the source of two version

    • SOURCE0: Handle app internal events, the app is responsible for managing (triggering), such as Uievent,cfsocket
    • Source1: Managed by Runloop and kernel, Mach port drives such as Cfmach, Cfmessage

Cfrunloopobserverref

Report Internal Runloop changes to the current state caanimation

The following points can be monitored at a point in time:

    Runloopobserver and Autorelease Pool

Uikit the Autorelease object generated in this loop by runloopobserver the pop and push of the autoreleasepool between two sleep runloop. (as if there were no release issues in Swift)

  

Cfrunloopmoderef

Runloop you need to pause the current loop and then restart the new Loopnsdefalutrunloopmode when the mode is only and must be replaced in a certain mode at the same time Default state. Idle state uitrackingrunloopmode????????????? Private, when the app starts Nsrunloopcommonmodes??? default includes the first and second

  

Cfrunlooptimerref
    • Cfrunlooptimerref is a time-based trigger (basically nstimer), a mode can have multiple timer (stored in Arrar)
 /** * The internal implementation of this method is: Create a timer, add to the default mode in Runloop, Runloop start this mode, take out this mode timer to use*/[Nstimer scheduledtimerwithtimeinterval:0.5target:self selector: @selector (run) Userinfo:nil Repeats:yes]; /** * The above code is equivalent to the following*/    //Create a timerNstimer *timer = [Nstimer timerwithtimeinterval:0.5target:self selector: @selector (run) Userinfo:nil Repeats:yes]; //The timer only runs in Nsdefaultrunloopmode mode, and once the Runloop enters another mode, the timer will not work[[Nsrunloop Currentrunloop] Addtimer:timer Formode:nsdefaultrunloopmode]; //If you drag, we add the timer to this nsrunloopcommonmodes marker.[[Nsrunloop Currentrunloop] Addtimer:timer formode:nsrunloopcommonmodes]; NSLog (@"-----------%@", [Nsrunloop Currentrunloop]); /** * The timer will run in the mode labeled Common modes (this mode is just a marker) * Runloop will look for a pattern with common tag, with this tag, can run * Print the current Runloop information output as: (with CO Mmon modes tags have two, uitrackingrunloopmode and Kcfrunloopdefaultmode), so timers can run in both modes, Runloop will only run a mode common modes = < Cfbasichash 0x7fb8b2700490 [0x10ec6ba40]>{type = mutable set, Count = 2, entries = 0: <cfstring 0X10FBA 2210 [0x10ec6ba40]>{contents = "Uitrackingrunloopmode"} 2: <cfstring 0x10ec8c5e0 [0x10ec6ba40]>{contents = " Kcfrunloopdefaultmode "}}*/

Create Runloop in Afnetworking

[[Nsthread CurrentThread] SetName:@ "afnetworking"*runloop = [Nsrunloop Currentrunloop]; [Runloop Addport:[nsmachport Port] Formode:nsdefalutrunloopmode] // been alive. [Runloop Run];

This is a good way to deal with network response

Uitrackingrunloopmode and Nstimer

// By default, Nstimer is added to the Nsdefalutrunloopmode // If you want Nstimer to be added to Nsrunloopcommonmodes by component or animation effects [[Nsrunloop currentrunloop]addtimer:timer...formode:nsrunloopcommonmodes];

What is the processing logic of Runloop?

Each time the run loop runs, the run loop pair of your thread automatically processes the previously unhandled message and notifies the relevant observer. The specific order is as follows:

    1. Notifies the watcher that the run loop has started
    2. Notifies the observer of any timer that is about to start
    3. Notifies the observer of any upcoming non-port-based sources
    4. Start any prepared non-port-based source
    5. If the port-based source is ready and in a wait state, start immediately and go to step 9.
    6. Notifies the watcher thread to enter hibernation
    7. Put a thread into hibernation until either of the following events occurs:
      • An event arrives at a port-based source
      • Timer start
      • Time for Run loop setting has timed out
      • Run loop is explicitly awakened
    8. Notifies the Observer that the thread will be awakened.
    9. Handling Unhandled Events
      • If the user-defined timer starts, the timer event is processed and the run loop is restarted. Go to step 2
      • If the input source is started, the corresponding message is passed
      • If the run loop is explicitly awakened and the time has not expired, restart the run loop. Go to step 2
    10. Notifies the Observer that run loop is finished.

Good articles are worth repeating, we in different stages to the same article or material can have different harvest, improve their understanding of knowledge, declare: It is best to understand and summarize once again, do not blindly collection, each programmer has become the potential of Daniel, only in the efforts. Refueling Technology House!

  

  

Personal insights on Runloop in 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.