In the software development process, we often need to execute a method after a certain period of time, or to follow a certain cycle of execution of a method. At this time, we need to use the timer.
However, there are many ways to accomplish these tasks in iOS, how many methods do you have? After consulting the data, there are about three ways: Nstimer, Cadisplaylink, GCD. I'll explain how they're used in the next step.
First, Nstimer
1. Create a method
| 1 |
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:) userInfo:nil repeats:NO]; |
-
TimerInterval : The time to wait before executing. For example, set to 1.0, which represents 1 seconds after the execution method
-
target : The object that needs to execute the method.
-
Selector : The method to be executed
-
repeats : whether to cycle
2. Release method
After calling the Create method, the target object's counter will be incremented by 1 until the execution is complete, automatically minus 1. If it is a loop execution, it must be closed manually, otherwise the release method may not be performed.
3. Features
The timing of the actual trigger event for a timer, whether it be a one-time or periodic, will be related to the Runloop and Runloop mode being added, and if the runloop is performing a continuous operation, the timer will be delayed. A repetitive timer encounters this situation, and if the delay exceeds a period, it is executed immediately after the delay and continues with the period specified earlier.
Using the creation method above, the timer is automatically added to the Mainrunloop Nsdefaultrunloopmode. If you create a timer using the following method, you must manually join the Runloop:
| 12 |
NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; |
Second, Cadisplaylink
1. Create a method
| 1234 |
```objc self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)]; [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];``` |
2. Stop method
| 12345 |
```objc [self.displayLink invalidate]; self.displayLink = nil;``` **当把CADisplayLink对象add到runloop中后,selector就能被周期性调用,类似于重复的NSTimer被启动了;执行invalidate操作时,CADisplayLink对象就会从runloop中移除,selector调用也随即停止,类似于NSTimer的invalidate方法。** |
3. Features
-
Called when the screen refreshes
Cadisplaylink is a timer class that allows us to draw specific content to the screen at a frequency that is synchronized with the screen refresh rate. Once the 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 end of the content refresh. The corresponding selector of the Cadisplaylink class is called once. So typically, follow the iOS device screen refresh rate 60 times/second
-
Delay
-
The screen refresh rate for iOS devices is fixed, and cadisplaylink is normally called at the end of each flush, with very high accuracy. However, if the calling method is more time-consuming than the screen refresh cycle, it can cause several callback invocation opportunities to be skipped.
-
If the CPU is too busy to guarantee a 60-time/second refresh rate on the screen, it will cause the chance to skip several calls to the callback method, depending on how busy the CPU is.
-
Usage Scenarios
It can be seen from the principle that Cadisplaylink is suitable for the continuous redrawing of the interface, such as video playback need to constantly get the next frame for the interface rendering.
4. Important Attributes
-
Frameinterval
The value of the Nsinteger type, used to set the interval for how many frames are called once selector method, the default value is 1, which is called once per frame.
-
Duration
The Cftimeinterval value of ReadOnly, which represents the interval between two screen refreshes. It is important to note that this property will not be assigned until the target's selector is first called. The call interval for selector is calculated by calling interval time = Durationxframeinterval.
Three, GCD way
| 12345 |
double delayInSeconds = 2.0;dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ //执行事件}); |
| 12345678 |
NSTimeInterval period = 1.0; //设置时间间隔dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行dispatch_source_set_event_handler(_timer, ^{ //在这里执行事件});dispatch_resume(_timer); |
Several timers in iOS