Analysis of Run loop in IOS

Source: Internet
Author: User

Analysis of Run loop in IOS

Although Runloop is the key concept that the thread wants to close, but the runloop in cocoa is not used much, the View related blog post has not got to get started its "why". So shallow to learn a few days, a humble share of the shallow, as a note, write down its why. There is no wrong or wrong place, also hope to advise, not very grateful.

Run Loop FAQ

When the thread finishes executing, it is destroyed. In order for the line Cheng Nen to run all the time, we can get a run loop inside the thread to keep the threads executing:

- (void)myThread:(id)sender{  while (TRUE) {    @autoreleasepool {      //do some jobs      //break in some condition      usleep(10000);    }  }}

OK, now the thread is able to run all the time. The new task is here: While this thread is running, you can add or remove different computing tasks from other threads as you go. This is the nsrunloop powerful place.
Let's now simply evolve:

Nsmutablearray *targetqueue; Nsmutablearray *actionqueue;-(void) MyThread: (ID) sender{ while(TRUE) {@autoreleasepool {//do Some jobs      //break in some conditionNsuinteger Targetcount = [TargetqueueCount]; for(NsuintegerIndex=0;Index< Targetcount; ++Index) {id target = targetqueue[Index]; SEL action = nsselectorfromstring (actionqueue[Index]);if([Target respondstoselector:action])        {[Target performselector:action withobject:nil]; }} usleep (10000); }  }}

From here, we can add the dynamically added code to Targetqueue and Actionqueue in other threads while adding objects and methods to it.
The so-called Runloop, is the following structure:

while (TRUE) {    //breakin some condition}

This structure is the runloop of the thread, which resembles the name of the Nsrunloop class, but is not actually a thing at all. What is that nsrunloop? Let's look at the following code:

 @interface mynstimer : nsobject {IDTarget SEL Action;floatInterval Cfabsolutetime Lasttime;} - (void) invoke;@end @implementation mynstimer - (void) invoke; {if([Target respondstoselector:action]) {[Target performselector:action withobject:Nil]; }}@end#!objc @interface mynsrunloop : nsobject {Nsmutablearray*timerqueue;} - (void) AddTimer: (mynstimer*) t;-(void) Executeonce;@end @implementation mynsrunloop - (void) AddTimer: (mynstimer*) t;    {@synchronized (timerqueue) {[Timerqueue addobject:t]; }}- (void) Executeonce;    {cfabsolutetime currenttime=cfabsolutetimegetcurrent (); @synchronized (timerqueue) { for(Mynstimer *t in Timerqueue) {if(currenttime-t. Lasttime>t. Interval) {T. Lasttime=currenttime;            [t invoke]; }        }    }}@end @interface mynsthread : nsobject {Mynsrunloop *runloop;} - (void) Main: (ID) sender;@end @implementation mynsthread - (void) Main: (ID) sender{ while(TRUE) {@autoreleasepool {//do Some jobs      //break in some condition[Runloop executeonce]; Usleep10000); }  }}@end

Come here, we are basically the RUNLOOP structure abstracted out. For example I have a mynsthread instance, MyThread1. I can add the required tasks to the thread of this instance, and the Mynsrunloop objects inside the myThread1 will manage these tasks.

*timer1=[MyNSTimer scheduledTimerWithTimeInterval:1 target:obj1 selector:@selector*timer2=[MyNSTimer scheduledTimerWithTimeInterval:2 target:obj2 selector:@selector(download2:)];[myThread1.runloop addTimer:timer2];
Run Loop model doubts

We know that in iOS, the user experience is extremely important. For example, the UITableView is very smooth when sliding, the interface update is responsible for the main thread, but even if we add more Nstimer scheduled tasks to the main thread in the default way, it will not affect the sliding of uitableview. How does the main thread do this? This is related to the run loop model.
Let's try to improve the code:

 @interface mynsrunloopmode : nsobject {  Nsmutablearray*_timerqueue;NSString*_name;} - (void) AddTimer: (Mynstimer *) timer;-(void) Executeonce;@end @interface mynsrunloop : nsobject {Nsmutableset *_modes; Mynsrunloopmode *_currentmode;} - (void) AddTimer: (mynstimer*) t;-(void) AddTimer: (Mynstimer *) T Formode: (NSString*) mode;-(void) Executeonce;@end//implementation file @implementation mynsrunloopmode - (void) executeonce {cfabsolutetime currenttime=cfabsolutetimegetcurrent (); @synchronized (timerqueue) { for(Mynstimer *t in Timerqueue) {if(currenttime-t. Lasttime>t. Interval) {T. Lasttime=currenttime;      [t invoke]; }    }  }}@end @implementation mynsrunloop - (void) AddTimer: (Mynstimer *) Timer {[ SelfAddtimer:timer formode:@"Nsdefaultrunloopmode"];} - (void) AddTimer: (Mynstimer *) Timer Formode: (NSString*) Modename {Mynsrunloopmode *mode =Nil; for(Mode in _modes) {if([Mode. NameIsequaltostring:modename]) { Break; }} [mode Addtimer:timer];} - (void) executeonce {[_currentmode executeonce];}@end

We have added another class: Mynsrunloopmode, which puts the execution of the Nsrunloop in the object of this class. The Nsrunloop has a set of mode and a currentmode. Runloop can only run under CurrentMode at any time, that is, it will only perform the tasks under that mode at this time. We can specify the mode of the current Nsrunloop: [NSRunLoop runMode:beforeDate:] .
The system defines several mode, and each model has its own name, one of which is nsdefaultrunloopmode. When we add a task to the run loop, we only need to specify the name of the model, and the task is added to the model.
I think you guessed it, because Nstimer is added to Nsdefaultrunloopmode by default, and when UITableView is sliding, the main thread is not in this Mode (instead of cutting into nseventtrackingrunloopmode), so Nstimer's mission will not be executed at all, and of course it will not have a slightest effect on the slide. After the slide, the main thread will also be cut into the nsdefaultrunloopmode, at this time the Nstimer task can be executed. Of course we can add Nstimer to any mode: [NSRunLoop addTimer:forModel:] .
How, the introduction of this mode is quite to force it!
  
This article introduces the basic principle of run loop, runloop the real situation is much more complex, then original aim, you have to be interested, you can also study its implementation.

Reference:
1, http://lianxu.me/2012/11/10-cocoa-objc-newbie-problems/
2, https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/ Runloopmanagement.html
  

Run loop in IOS

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.