RunLoop literally mean operating cycle;
Its fundamental role: to maintain continuous operation of the program;
App handle various events in (for example: a touch event, timer event, Selector event)
Saving CPU resources, improve program performance: Things work when the rest when the rest
1.main function of RunLoop
int main ( int argc, char * the argv []) { @autoreleasepool { return UIApplicationMain (argc, the argv, nil, NSStringFromClass ([the AppDelegate class ])); } } In this main function, the internal function UIApplicationMain started a RunLoop Therefore UIApplicationMain function has not returned, maintaining continuous operation of the program. The default start RunLoop is associated with the main thread.
NSRunLoop is based CFRunLoopRef OC layer packaging, so understanding RunLoop internal structure, need more research CFRunLoopRef-level API.
2.RunLoop relationship with thread
Each thread has a corresponding unique objects of RunLoop
main thread of RunLoop has been automatically created, the child needs to take the initiative to create a thread RunLoop
RunLoop created when you first get destroyed at the end of the thread
to obtain the corresponding sub-thread runLoop (ie, currentRunLoop) which itself is lazy loaded, if the first call will be to create a thread corresponding runLoop current and saved, subsequent calls to the direct access
3.RunLoop acquisition
#pragma Mark - runloop - ( void ) the touchesBegan: (NSSet <the UITouch *> *) Touches withEvent: (UIEvent *) Event { // -OC language in the API // 01 corresponding to the main thread acquires the object runloop the NSRunLoop mainRunloop * = [ mainRunLoop NSRunLoop]; // 02 runloop get the current object NSRunLoop * currentRunLoop = [NSRunLoop currentRunLoop]; NSLog ( @ " % the p---- the p-% " , mainRunloop, currentRunLoop); // C language API // 01 primary circulating CFRunLoopRef mainRunloopRef = CFRunLoopGetMain (); // 02 current operating cycle CFRunLoopRef currentRunloopRef = CFRunLoopGetCurrent(); NSLog(@"%p---%p", mainRunloopRef, currentRunloopRef); //转化 NSLog(@"%p----%p", mainRunloop.getCFRunLoop, mainRunloopRef); }
Print results:
2019-09-18 15:31:31.176193+0800 NSCach[60622:1117017] 0x60000184c060---0x60000184c060 2019-09-18 15:31:31.176302+0800 NSCach[60622:1117017] 0x600000050600---0x600000050600 2019-09-18 15:31:31.176362+0800 NSCach[60622:1117017] 0x600000050600----0x600000050600
As can be seen, the main operating cycles of the current cycle is currently running the runloop the same, can be seen in the last line, OC acquired runloop runloop and C may be transformed into each other.