Implementation of iOS timer NSTimer, CADisplayLink, and GCD3, and quartz Timer
In the process of software development, we often need to execute a method after a certain time, or always execute a method according to a certain cycle. At this time, we need to use a timer.
However, there are many methods in iOS to complete the above tasks. How many methods are there? After reading the information, there are three methods: NSTimer, CADisplayLink, and GCD. Next I will introduce their usage one by one.
I. NSTimer
1. Creation Method
1 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:) userInfo:nil repeats:NO];
TimerInterval: The waiting time before execution. For example, if it is set to 1.0, it indicates the method to be executed in 1 second.
Target: The object of the method to be executed.
Selector: Method to be executed
Repeats: Whether loop is required
2. Release Method
1 [timer invalidate];
After the creation method is called, the counter of the target object is incremented by 1 until the execution is completed, and 1 is automatically subtracted. If it is executed cyclically, you must manually disable it; otherwise, you can skip the release method.
3. Features
Whether it is a one-time or periodic timer's actual trigger event time, it will be related to the added RunLoop and RunLoop Mode. If this RunLoop is executing a continuous operation, timer will be delayed. In this case, if the delay exceeds a cycle, the timer runs immediately after the delay ends and continues the execution according to the specified cycle.
Using the above creation method, timer is automatically added to NSDefaultRunLoopMode of MainRunloop. If you use the following method to create a timer, you must manually add the Runloop:
1 NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];2 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
UIScrollView executes UITrackingRunLoopMode when dragging, which will pause the timer and resume the timer only when it is restored to NSDefaultRunLoopMode.
Therefore, if the timer is required to be dragged by UIScrollView, we recommend that you add it to UITrackingRunLoopMode or nsunloopcommonmodes:
1 NSTimer * timer = [NSTimer timerWithTimeInterval: 5 target: self selector: @ selector (timerAction) userInfo: nil repeats: YES]; 2 [[nsunloop mainRunLoop] addTimer: timer forMode: UITrackingRunLoopMode]; // <or nsunloopcommonmodes
Ii. CADisplayLink
1. Creation Method
1 self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)]; 2 [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
2. Stop Method
1 [self. displayLink invalidate]; 2 self. displayLink = nil; 3 4/** when the CADisplayLink object is added to the runloop, the selector can be periodically called, similar to the repeated NSTimer being started; when the invalidate operation is executed, the CADisplayLink object is removed from runloop, And the selector call is stopped immediately, similar to the invalidate method of NSTimer. **/
3. Features
Call when screen refreshing
CADisplayLink is a Timer class that allows us to draw specific content to the screen at a frequency that synchronizes with the screen update rate. After CADisplayLink is registered to runloop in a specific mode, runloop sends a specified selector message to the target specified by CADisplayLink whenever the screen displays the content refreshed, the selector corresponding to the CADisplayLink class will be called once. Therefore, the screen update rate for iOS devices is usually 60 times per second.
Latency
The screen refresh frequency of iOS devices is fixed. CADisplayLink is normally called at the end of each refresh, with a high accuracy. However, if the called method is time-consuming and exceeds the screen refresh cycle, several callback call opportunities will be skipped.
If the CPU usage is too busy and the screen refreshing rate cannot be guaranteed for 60 times/Second, several chances of calling the callback method will be skipped. The number of skipping times depends on the CPU usage.
Use Cases
It can be seen from the principle that CADisplayLink is suitable for non-stop screen repainting. For example, you need to continuously obtain the next frame during video playback for interface rendering.
4. Important attributes
FrameInterval
Specifies the number of frames at which the selector method is called. The default value is 1, that is, each frame is called.
Duration
The CFTimeInterval value of readOnly, indicating the interval between two screen refreshes. Note that this attribute is assigned a value only after the target selector is called for the first time. The call interval Calculation Method of selector is as follows: Call interval = duration × frameInterval.
Iii. GCD Mode
Run Once
1 double delayInSeconds = 2.0; 2 dispatch_time_t popTime = dispatch_time (DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 3 dispatch_after (popTime, interval (), ^) {4 // execution event 5 });
Repeated execution
1 NSTimeInterval period = 1.0; // set the interval of 2 dispatch_queue_t queue = queue (queue, 0); 3 dispatch_source_t _ timer = dispatch_source_create (queue, 0, 0, queue ); 4 dispatch_source_set_timer (_ timer, dispatch_walltime (NULL, 0), period * NSEC_PER_SEC, 0); // execute 5 dispatch_source_set_event_handler (_ timer, ^ {6 // execute event 7}); 8 dispatch_resume (_ timer );
1. Creation Method
// You need to set dispatch_source_t timer as a member variable. Otherwise, @ property (nonatomic, strong) dispatch_source_t timer will be released immediately; // NSTimeInterval delayTime = 3.0f; // timer interval NSTimeInterval timeInterval = 3.0f; // create a subthread queue dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ); // use the created queue to create the timer _ timer = dispatch_source_create (DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); // set the delayed execution time, delayTime is the number of seconds to be delayed. interval startDelayTime = dispatch_time (interval, (int64_t) (delayTime * NSEC_PER_SEC); // sets the timer (_ timer, startDelayTime, timeInterval * NSEC_PER_SEC, 0.1 * NSEC_PER_SEC); dispatch_source_set_event_handler (_ timer, ^ {// execution event}); // start the timer dispatch_resume (_ timer)
2. Stop Method
dispatch_source_cancel(_timer);
3. Important attributes
Add to favorites,