RunLoop series
In layman's language RunLoop (a): acquaintance
layman RunLoop (2): The data structures
in layman's language RunLoop (c): event loop mechanism
layman RunLoop (four): RunLoop thread
layman RunLoop (five): RunLoop and NSTimer
layman RunLoop (VI): Related interview questions
RunLoop Profile
- Operating cycle, the program is running loop to do something (e.g., receiving a message, processing the message, the sleep waiting, etc.);
RunLoop
The object is to carry out a management of events / messages through the event loop internally maintained;RunLoop
Is not a simpledo...while
loop, it relates to the switching between the user mode and kernel mode.
Event Loop
Event loop is the event / message management, event loop can be achieved:
- When no messages to process, dormant thread to avoid resource consumption. Switch from user mode to kernel mode, waiting for a message;
- When there are messages to process immediately wake up the thread back to the user mode process messages;
- By calling the
mach_msg()
function to transfer control to the kernel state of the current thread / user mode.
The basic role of RunLoop
- To maintain continuous operation of the program:
If you do notRunLoop
,main()
the function to perform a complete, the program will quit immediately.
Our iOS program to keep the reason is that in continuous operationmain()
calls a function inUIApplicationMain
a function, this function will start inside the main threadRunLoop
; - Handle various events (such as touch events, timer events, etc.) App of the;
- Saving CPU resources, improve program performance: When you do things that work, rest upon the rest.
RunLoop application areas
- Timer (Timer), PerformSelector
- GCD:dispatch_async(dispatch_get_main_queue(), ^{ });
- Incident response, gesture recognition interface refresh
- Network requests
- AutoreleasePool
RunLoop objects
- There are 2 sets of iOS API to access and use
RunLoop
:
① Foundation:NSRunLoop
(aCFRunLoopRef
package that provides object-oriented API)
② Core Foundation:CFRunLoopRef
NSRunLoop
AndCFRunLoopRef
they represent theRunLoop
objectsNSRunLoop
Not open source, butCFRunLoopRef
open source: Core Foundation Source- Gets
RunLoop
the object of ways:
// Foundation
[NSRunLoop mainRunLoop]; // 获取主线程的 RunLoop 对象
[NSRunLoop currentRunLoop]; // 获取当前线程的 RunLoop 对象
// Core Foundation
CFRunLoopGetMain(); // 获取主线程的 RunLoop 对象
CFRunLoopGetCurrent(); // 获取当前线程的 RunLoop 对象
Application RunLoop in the actual development of
- Using port or custom input sources to communicate with other threads
- Use timers on child thread
- Solve the
NSTimer
problem stops working when the slide - Control thread life cycle, to achieve a permanent thread
- In any Cocoa application
performSelector...
method - Monitoring applications Caton
- Performance Optimization
- …
Related Links
Core Foundation Source
Apple's official documentation RunLoop