About RunLoop and runloop
First, we need to first understand this RunLoop;
The nsunloop is a class in the Cocoa framework, and the CFRunLoopRef class in the Core Fundation.
The difference between the two is that the former is NOT thread-safe, while the latter is thread-safe.
RunLoop Application
Generally, you do not need to create or start RunLoop. In either case, you must manually set it:
Use the timer in the thread Separation
The implementation of the timer is based on the RunLoop. In normal times, we may not perform any operations on the RunLoop by using the timer, because the main thread RunLoop is started by default, if we need to repeat an action in the Child thread, We need to manually add
[[Nsunloop currentRunLoop] run];
Each thread has a unique RunLoop object.
The RunLoop of the main thread has been automatically created. The RunLoop of the sub-thread needs to be automatically created.
RunLoop is created when it is obtained for the first time and destroyed when the thread ends.
Purpose:
A. Keep the program running continuously (why does the iOS program keep alive)
B. process various events in the APP (such as touch events, Timer events NSTimer, selector events [Timer mselector)
C. save CPU resources and improve program performance. If there is something to do, you can rest.
If there is no RunLoop, the program will exit at startup and nothing can be done.
If RunLoop exists, it is equivalent to an internal endless loop, which can ensure the continuous operation of the program.
What makes RunLoop more powerful is message listening. Because of the thread security advantages of CFRunLoopRef, we usually use the latter more.
When the input source is registered in Runloop, a method is used to remove the input source, but the timer does not, but the invalidate method in the timer can be removed from runloop, as described in the official documentation: invalidate is important and the only method that can deregister the timer from the runloop. Therefore, if we create a timer, we must call the invalidate method when not in use.