IOS Runloop message loop, iosrunloop

Source: Internet
Author: User

IOS Runloop message loop, iosrunloop

  • Introduction

Runloop is an event listening loop, which can be understood as a while endless loop. When an event is monitored, the system can rest.
Runloop can be switched in different modes. iOS has five modes. Among them, the UIInitializationRunLoopModel application is used when it is started and will not be used after it is started. GSEventReceiveRunLoopMode accepts the internal Model of the system, it is usually not possible. There are also three modes, namely begin, NSDefaultRunLoopMode, and nsunloopcommonmodes, which are commonly used. We will explain in detail in the following section. Among these modes, nsunloopcommonmodes is a placeholder, and NSDefaultRunLoopMode and uitr.

  • Runloop

-1.1 literal meaning

A running cycle B running circle

-1.2 Basic functions (important)

(1) Keep the program running continuously (why is the ios program always alive?) (2) process various events in the app (such as touch events, Timer events [NSTimer], selector events [selector · performSelector ·]) (3) save CPU resources and improve program performance, do things if there is something, and rest if there is nothing

-1.3 Important Notes

(1) If there is no Runloop, the program will exit as soon as it is started, and nothing can be done. (2) If Runloop exists, it is equivalent to an internal endless loop, which can ensure the continuous running of the Program (3) Runloop (4) in main Function) A Runloop is started in the UIApplication function. The function returns an int value (5). The default Runloop is associated with the main thread.

-1.4 Runloop object

(1) There are two APIs in iOS development to access Runloop. foundation framework [nsunloop] B. core foundation framework [CFRunloopRef] (2) Both nsunloop and CFRunLoopRef represent the RunLoop objects. They are equivalent and can be converted to each other (3) That is a layer of OC Packaging Based on CFRunLoopRef, therefore, to understand the internal structure of RunLoop, you need to study the APIS at the CFRunLoopRef level (Core Foundation level)

-1.5 Runloop references

(1) Apple official documentation: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html (2) CFRunLoopRef open source code: http://opensource.apple.com/source/CF/CF-1151.16/

-1.6 Runloop and thread

(1) Relationship between Runloop and thread: A Runloop corresponds to a unique thread question: how to keep the Sub-thread dead? Answer: enable the creation of a Runloop for this sub-thread (2: the main thread Runloop has been created, and the Child thread's runloop needs to be manually created (3) the Runloop lifecycle: created at the first acquisition and destroyed at the end of the thread

-1.7 get the Runloop object

(1) obtain the current Runloop object. <G id = "1"> </G> <G id = "2"> </G>. CFRunLoopRef runloop2 = CFRunLoopGetCurrent (); (2) Get the main Runloop of the current application (the Runloop corresponding to the main thread). nsunloop * runloop1 = [nsunloop mainRunLoop]; B. CFRunLoopRef runloop2 = CFRunLoopGetMain (); (3) Note: Create a runloop by calling the currentRunLoop method instead of the alloc init method, it is a lazy task. (4) If the child thread does not take the initiative to obtain the Runloop, the Child thread will not create the Runloop. You can download the source code of CFRunloopRef, search for _ CFRunloopGet0, and view the code. (5) The Runloop object is stored using dictionaries, and the key is the corresponding thread Value for the corresponding Runloop of the thread.

-1.8 Runloop-related classes

(1) Runloop running principle diagram (2) Five Related Classes. CFRunloopRef B. CFRunloopModeRef [Runloop running mode] c. CFRunloopSourceRef [event source to be processed by Runloop] d. CFRunloopTimerRef [Timer event] e. CFRunloopObserverRef [observer of Runloop (listener)] (3) relationship diagram between Runloop and related classes (4) to run Runloop, it must have a internal mode, in this mode, source \ observer \ timer must exist. At least one of them must exist.

-CFRunloopModeRef

(1) CFRunloopModeRef indicates the running mode of Runloop (2) One Runloop can have multiple modes, and one mode can have multiple source \ observer \ timer (3) only one mode can be specified when a runloop is started. This mode is called the current mode of the Runloop (4). If you need to switch the mode, you can only exit the current Runloop first, re-specify a mode to enter (5). In this way, the system separates the timers of different groups so that they are not affected. (6) The system registers 5 mode a by default. kCFRunLoopDefaultMode: the default Mode of the App. Generally, the main thread runs B in this Mode. UITrackingRunLoopMode: interface tracking Mode, used for ScrollView tracking touch sliding, ensure that the interface sliding is not affected by other modes c. UIInitializationRunLoopMode: Enter the first Mode when the App is started. After the App is started, d is no longer used. GSEventReceiveRunLoopMode: Internal Mode for accepting system events. e is usually not used. kCFRunLoopCommonModes: This is a placeholder Mode, not a real Mode.
  • Three other Runloop Modes

→ UITrackingRunLoopMode: (Priority switch !!) This mode is the mode in which Runloop switches when UI events are interacted !!!

Scenario: This mode has the highest priority. When UI events are interacted, the mode is switched to this mode first.

The test code is as follows:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 repeats:YES block:^(NSTimer * _Nonnull timer) {  NSLog(@"current Runloop = %@", [NSRunLoop currentRunLoop].currentMode);}];[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

Result:

Current Runloop = kCFRunLoopDefaultMode // default mode during execution current Runloop = UITrackingRunLoopMode // when the page is sliding, The UITextView mode is automatically switched to this mode first. Current Runloop = kCFRunLoopDefaultMode // when the UITextView operation on the page is not performed, It is restored to the default mode.


→ NSDefaultRunLoopMode: Default Runloop mode! Handle any event!

Scenario: default mode. If an event exists, the system automatically switches to this mode.

The test code is as follows:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 repeats:YES block:^(NSTimer * _Nonnull timer) {  NSLog(@"current Runloop = %@", [NSRunLoop currentRunLoop].currentMode);}];

Result:

Current Runloop = kCFRunLoopDefaultMode // This mode is enabled by default after the program is started.

→ Nsunloopcommonmodes: placeholder !! (In default and UITrackingRunLoopMode !)

Scenario: This is mainly used to add an NSTimer to the RunLoop. A tag is essentially not a Mode. By default, both NSDefaultRunLoopMode and NSTrackingRunLoopMode are bound to this tag.

Instance code:

Static int I = 0; NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval: 1 repeats: YES block: ^ (NSTimer * _ Nonnull timer) {lable. text = [NSString stringWithFormat: @ "always currently displayed index: % zi", ++ I] ;}]; [[nsunloop currentRunLoop] addTimer: timer forMode: nsunloopcommonmodes];

Special instructions:
1. A thread object corresponds to a RunLoop object. After the MainRunLoop object is created, the MainRunLoop object is started by default. Inside it is a do-while loop.
2. The main thread will start a Runloop by default, and the sub-thread will not start the Runloop automatically and we need to start it manually. See the following code.

Static int I = 0; queue = dispatch_queue_create (0, 0); // enable a sub-thread dispatch_async (queue, ^ {NSTimer * timer = [NSTimer timerWithTimeInterval: 1 repeats: YES block: ^ (NSTimer * _ Nonnull timer) {NSLog (@ "display result = % zi, % @", ++ I, [nsunloop currentRunLoop]. currentMode) ;}]; [[nsunloop currentRunLoop] addTimer: timer forMode: nsunloopcommonmodes]; [[nsunloop currentRunLoop] run]; // start Runloop manually });

 

  • Illustration

  • Runloop Summary

It can be seen that the running thread will always exist. This is because no event is in sleep state, and an event is in working state. To save CPU resources. In this way, a thread can become a resident thread, that is, the thread has been present.

RunLoop is the core mechanism of iOS Event Response and task processing. It runs through the entire iOS system.

RunLoop is an event running Loop Mechanism that keeps applications running continuously. Because of this mechanism, the application can be in sleep state when no event occurs and when an event occurs, it is in the working state. To save CPU resources. This is also a major feature of it.

The nsunloop is a class in the Cocoa framework and corresponds to it. It is a CFRunLoopRef class in the Core Foundation. The difference between the two is that the former is NOT thread-safe, the latter is thread-safe, and the two can be converted to each other.

Relationship between RunLoop and thread:
RunLoop is used to manage threads. Each thread corresponds to a RunLoop object. We cannot create the RunLoop object of the current thread, but we can get the RunLoop object of the current thread. RunLoop is used to monitor whether an event occurs in the thread. If it does, it will work and sleep if it does not.

The RunLoop object of the main thread is enabled by default, but not of other threads by default.

RunLoop and AutoreleasePool;

The event type processed by RunLoop;

RunLoop running mode;

Related Article

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.