A probe into the mechanism of Runloop in iOS

Source: Internet
Author: User

A probe into the mechanism of Runloop in iOSFirst, shallow knowledge runloop

Runloop this guy in iOS development, we have been using, but never notice him, not even seen his face, that this mysterious guy what exactly do? First, let's take a look at our program operating mechanism.

Whether it is an object-oriented language or a process-oriented language, the execution of code is ultimately process-oriented. Threads are also the same, where a thread executes from the start code to the end code to destroy. Just like the Hello World program, the program ends when you print out a string, so how does our app implement the following mechanism: The app is on standby from the start of the run, receives a user interaction like a click event, and then waits for an interactive response after it finishes, Until we kill the program. Through the analysis of this process, we may guess that the main thread we execute must be in a dead loop, hibernate when there is no task, and be activated to perform the task after receiving the task. Now we can understand that the mechanism by which a management thread executes a task is the runloop mechanism, in which the sleep and activation of a thread is managed by the Runloop object.

second, the relationship between Runloop and thread

As we said above, Runloop is used to manage threads, so what are their direct relationships and how do they interact? In fact, each thread has a Runloop object, which can be obtained by means of a specific method. Here's one thing to note, as the official documentation describes, although each thread can get the Runloop object, but not every thread has this instance object, we can understand this: if we do not get runloop, this runloop does not exist, when we get, If it does not exist, it will be created. In the main thread, this mainrunloop is created by default and runs active.


Iii. Understanding Nsrunloop

Nsrunloop is a class in the cocoa framework and corresponds to the Cfrunloopref class in the core fundation. The difference between the two is that the former is not thread-safe and the latter is thread-safe. Here we only discuss the properties and methods of Nsrunloop:


+ (Nsrunloop *) Currentrunloop;

Gets the runloop of the current thread: either gets, none is created


+ (Nsrunloop *) Mainrunloop;

Get the Runloop of the main thread


@property (readonly, copy) NSString *currentmode;

Gets the execution mode of the current Runloop, and the two modes are as follows:

NSString * Const Nsdefaultrunloopmode;

Default mode, receiving responses from most input sources

NSString * Const nsrunloopcommonmodes;

A collection of multiple modes


-(CFRUNLOOPREF) Getcfrunloop;

Gets the Cfrunloopref object for Runloop


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

Adding timers to the Runloop


-(void) AddPort: (Nsport *) Aport Formode: (NSString *) mode;

Adding the input source port to Runloop, the Nsport object can be understood as a detailed vector that will deliver the message with its proxy.


-(void) RemovePort: (Nsport *) Aport Formode: (NSString *) mode;

To remove an input source port


-(NSDate *) Limitdateformode: (NSString *) mode;

Get the next response time

Explanation: For example, the execution of the timer, it is not to call the method at the interval of time, but after the timer registers in the Runloop, the Runloop will set one time point to make the call, for example 10,20,30. If you miss a point in time, the timer does not delay the call, but waits for the next point in time, so the timer is not accurate.


-(void) Acceptinputformode: (NSString *) mode beforedate: (NSDate *) limitdate;

Receive a response before a certain time period


-(void) run;
Start running


-(void) Rununtildate: (NSDate *) limitdate;

Run to a point in time


-(BOOL) RunMode: (NSString *) mode beforedate: (NSDate *) limitdate;

Run before a certain deadline


iv. Application of Runloop

as we have said before, we have been using him, but we seldom see him. And, in most cases, we don't need to create or start runloop explicitly, but in two cases we have to set it up manually:

1. Using Timers in sub-threading

the implementation of the timer is based on Runloop, usually we use the timer you may not do anything to runloop, that is because the main thread of the Runloop default is open to run, if we in the sub-thread also need to repeat an action, as follows:

-(void) viewdidload {[Super viewdidload];    Additional setup after loading the view, typically from a nib.    Queue = Dispatch_queue_create ("Myqueue", dispatch_queue_concurrent); Dispatch_async (Queue, ^{nstimer * timer = [Nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector    (time) Userinfo:nil Repeats:yes];    }); }-(void) time{NSLog (@ "Run");}

You will find that after the program has run and does not print any information, the method is not called, we must manually execute the following code in the thread:

[[Nsrunloop Currentrunloop] run];

Timer to work properly.

2, when you use the following methods in the thread

Some of the delay functions and selectors used in the sub-threading, we must also manually open the Runloop, these methods are as follows:

@interface NSObject (nsdelayedperforming)

-(void) Performselector: (SEL) Aselector withobject: (ID) anargument afterdelay: (nstimeinterval) Delay Inmodes: (NSArray *) modes;

-(void) Performselector: (SEL) Aselector withobject: (ID) anargument afterdelay: (nstimeinterval) delay;

+ (void) Cancelpreviousperformrequestswithtarget: (ID) atarget selector: (SEL) Aselector object: (ID) anargument;

+ (void) Cancelpreviousperformrequestswithtarget: (ID) atarget;


-(void) Performselector: (SEL) Aselector target: (ID) target argument: (ID) arg order: (Nsuinteger) Order modes: (Nsarray *) Modes

-(void) Cancelperformselector: (SEL) Aselector target: (ID) target argument: (ID) arg;
-(void) Cancelperformselectorswithtarget: (ID) target;


v. Supplementary

Runloop is more powerful in listening to messages, because of the CFRUNLOOPREF thread security advantage, we usually use the latter more often.

careful you may find that the input source is registered into the Runloop, there will be a way to remove, but the timer is not, but the Invalidate method in the timer can be removed from the Runloop, as the Official document description: Invalidate is important and the only way to unregister a timer from Runloop, so if we create a timer, we must call the Invalidate method when not in use. I don't know why Apple separates the timer method, probably because it allows developers to explicitly call the Runloop method, and if you know why, ask for a message.

The question about timers is described in another blog post: http://my.oschina.net/u/2340880/blog/398598.



Learn to use welcome reprint

Where the omission is welcome

A probe into the mechanism of Runloop in iOS

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.