IOS Runloop Understand and use

Source: Internet
Author: User


Runloop

Last time I talked about runtime, this is Runloop, although both are the noun terms at the beginning of run, but in OC, these two things are not connected. This article is mainly about some concepts and usages of runloop. These include:

    • What Runloop?
    • How does Runloop exist?
    • What is included in the Runloop?
    • Use of runloop in daily development scenarios
first, what is Runloop

A very easy to imagine phenomenon: when we unlock the phone into an app, if you do not operate the phone (including the behavior of the network request), the phone will not have any reaction, once we have to operate, the phone will perform the response action.  So what's the phone doing when we're not working? If the state to be detected, you will find that the CPU usage is almost zero, that is, no operation when the state of the phone is dormant! Professional seems to say that when the phone does not accept the event, the phone automatically into hibernation, but to maintain a ready-to-wake posture, waiting for the user's event incoming. This mechanism is found in many different systems and is called an event loop. In Apple, the realization of this mechanism is runloop.

We'll probably think of Runloop as a do-while loop that will continue to execute the loop without accepting the exit instruction. Runloop adds more complex logic on top of this, allowing Runloop not only to hibernate without event input, but also to respond to events anytime, anywhere.

Logically, it can be understood as the following code.

func Loop () {    do  {        var message = get_next_message ();        Process_message (message);   Processing Information     while (message! = quit);} 

Of course, it's actually much more complicated than that. At least I don't think I can do some precise control in this loop. Let's take a look at some of the other things that are included in Runloop.

First look at Nsrunloop. Nsrunloop is a CF Runloopref-based package, but the two are not toll-free briged, which can be obtained in OC using the following method.

[Arunloop  Getcfrunloop];

Look at Apple's introduction to Nsrunloop:

The NSRunLoop class declares the programmatic interface to objects that manage input sources. An NSRunLoop object processes input to sources such as mouse and keyboard events from the window System, NSPort objects, and objects. An NSRunLoop object also processes NSTimer events.

Nsrunloop the input events for the hypervisor, which contain events from the window mouse and keyboard, as well as Nsport port events and network request events, and also include a timer event. That is, all events will be managed by Runloop and executed in an orderly manner in the app.

Second, how the Runloop exist

In Apple's Nsrunloop file we see these:

Foundation_export NsrunloopmodeConstNsdefaultrunloopmode; Foundation_export NsrunloopmodeConstNsrunloopcommonmodes@property (class,ReadOnly, strong) Nsrunloop *Currentrunloop; @property (class,ReadOnly, strong) Nsrunloop *Mainrunloop ns_available (10_5, 2_0);#endif@property (Nullable,ReadOnly, copy) Nsrunloopmode CurrentMode;-(cfrunloopref) getcfrunloop cf_returns_not_retained;- (void) AddTimer: (Nstimer *) Timer Formode: (nsrunloopmode) mode;- (void) AddPort: (Nsport *) Aport Formode: (nsrunloopmode) mode;- (void) RemovePort: (Nsport *) Aport Formode: (nsrunloopmode) mode;-(Nullable NSDate *) Limitdateformode: (nsrunloopmode) mode;- (void) Acceptinputformode: (nsrunloopmode) mode beforedate: (NSDate *) limitdate;@end@interfaceNsrunloop (nsrunloopconveniences)- (void) run; - (void) Rununtildate: (NSDate *) limitdate;-(BOOL) RunMode: (nsrunloopmode) mode beforedate: (NSDate *) limitdate;#if(Target_os_mac &&!) (target_os_embedded | | Target_os_iphone))-(void) Configureasserver ns_deprecated (10_0, 10_5, 2_0, 2_0);#endif///schedules the execution of a block on the target run loop in given modes.///-Parameter:modes An array of input modes for which , the block may be executed.///-Parameter:block The block to execute- (void) Performinmodes: (nsarray<nsrunloopmode> *) modes BLOCK: (void(^) (void)) Block Api_available (MacOSX (10.12), iOS (10.0), watchOS (3.0), tvOS (10.0));///schedules the execution of a block on the target run loop.///-Parameter:block The block to execute- (void) Performblock: (void(^) (void)) Block Api_available (MacOSX (10.12), iOS (10.0), watchOS (3.0), tvOS (10.0));

In this, I found that it could not be created in some way. Normal object objects can generally be created by Init. However, Nsrunloop did not. But we can see that Nsrunloop has a property:

@property (classreadonly, strong) Nsrunloop *currentrunloop;

in fact, Nsrunloop cannot be created directly, only through Currentrunloop. And each runloop can only operate on the current thread, because Runloop is not thread-safe. Read the Meow technology blog should know that Nsrunloop is based on the Cfrunloop package, and Cfrunloop is a pure C API, it is thread-safe. This has been mentioned in the thread, in fact, is to illustrate that nsrunloop depends on the thread, and each thread up to only one nsrunloop, for the main thread, in the app startup, the main function has opened a nsrunloop for the service main thread, This runloop can be obtained by Nsrunloop's Mainrunloop. If it is cfrunloop, you can get runloop of the current thread's runloop and main threads through Cfrunloopgetmain () and Cfrunloopgetcurrent ().

The thread and Runloop one by one correspond, when the thread is destroyed, Runloop also GG. Therefore, to maintain a runloop, the first thing to do is to ensure the state of the thread. The relationship is kept in a global Dictionary. The line Cheng Gang is created without runloop, and if you don't get it, it will never be there. Runloop is created when the first fetch occurs, the destruction of runloop occurs at the end of the thread. You can only get its runloop inside a thread (except for the main threads).

Iii. what is included in the Runloop?

Runloop manages events in threads that include: Timer events, source events, and observer. It also contains the model-runloopmode of the event's run.

Timer events are the timers we use.

The source event consists of two classes, one for Source0 and one for Source1, and the other is the difference between:

? Source0 only contains a callback (function pointer), which does not actively trigger events. When used, you need to call cfrunloopsourcesignal (source), mark the source as pending, and then manually invoke Cfrunloopwakeup (Runloop) to wake the Runloop and let it handle the event.
? Source1 contains a mach_port and a callback (function pointer) that is used to send messages to each other through the kernel and other threads. This Source can actively awaken Runloop threads.

Observer is the observer, it can listen to the runloop running state, can listen to the following states:

    kcfrunloopentry          = (1ul <<< Span class= "crayon-h" > 0) //about to enter loop     kcfrunloopbeforetimers   = ( Span class= "CRAYON-CN" >1ul << 1) , //about to process Timer     kcfrunloopbeforesources = ( 1ul << 2, //about to process Source     kcfrunloopbeforewaiting = ( 1ul << 5, //going into hibernation     kcfrunloopafterwaiting   = ( Span class= "CRAYON-CN" >1ul << 6) , //just woke up from hibernation kcfrunloopexit = (1UL << 7), //Near Exit Lo Op

Runloopmode: This is a marker of runloop. It has several forms:

1. The default mode of the Kcfrunloopdefaultmode:app, usually the main thread is running in this mode.
2. Uitrackingrunloopmode: interface Tracking mode for ScrollView tracking touch swipe to ensure that the interface is not affected by other mode when sliding.
3. Uiinitializationrunloopmode: The first Mode that was entered when the APP was launched is no longer used when the boot is complete.
4:gseventreceiverunloopmode: Accepts internal Mode for system events, which is usually not available.
5:kcfrunloopcommonmodes: This is a placeholder Mode that has no practical effect.

The timer, source, and observer mentioned above are not placed directly in the Runloop, but are labeled as item in a model, and then runloop run in the corresponding model to manage the item. When we are dealing with an item, first make sure the item is in the Runloop corresponding mode.

Four, the use of runloop in the daily development of the scene

Runloop in the daily development, the use of the scene is relatively small. We often have a situation where if you use a timer to perform a small animation, you will be paused when you drag the ScrollView. This is because Runloop typically runs in Kcfrunloopdefaultmode, which means that the nstimer created directly will be in this model. When you drag the ScrollView, runloop switch to Uitrackingrunloopmode, before the item in Kcfrunloopdefaultmode is no longer being runloop maintained, it stops running. To solve this, you just have to pass

-(void) AddTimer: (Nstimer *) Timer Formode: (nsrunloopmode) mode;

Add the Nstimer to the Uitrackingrunloopmode. There is another way, in all mode, there is a kcfrunloopcommonmodes, which is similar to its name, when the public mode, which is the item in this mode, will be supported by all mode. We can mark Nstimer as Commonmode to achieve the same goal.

There are other similar situations where we can see the use of Runloop in the famous afnetworking:

+ (void) Networkrequestthreadentrypoint: (IDobject  {    @autoreleasepool {        [[ Nsthread CurrentThread] SetName:@ "afnetworking"];         *runloop = [Nsrunloop currentrunloop];        [Runloop Addport:[nsmachport Port] formode:nsdefaultrunloopmode];        [Runloop run];    

This opens a thread, opens Runloop, and adds a port event to hold the Runloop running, but Port does not send a message about the timing. This thread is afnetworking used to place nsurlconection in the background processing requests and callbacks.

Y God's article: http://blog.ibireme.com/2015/05/18/runloop/

IOS Runloop Understand and use

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.