iOS timer selection
In iOS applications, timers are often needed to handle certain tasks, such as executing animations, updating the UI, etc. iOS offers a variety of timer types, including CADisplayLink, NSTimer, and GCD timers. Different timer types are suitable for different scenarios and requirements, so when selecting timer types, you need to choose according to the specific situation.
CADisplayLink
CADisplayLink is a timer type that allows you to execute a piece of code every second when the screen is updated. The CADisplayLink timer has very high accuracy because it is synchronized with the screen refresh frequency, so it ensures the smoothness of the animation. In addition, the method of calling the CADisplayLink timer is done via RunLoop, so it is thread-safe.
The steps to use the CADisplayLink timer are as follows:
- Create a CADisplayLink object.
- Set the target and selector of the timer.
- Add CADisplayLink to RunLoop.
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSTimer
NSTimer is another commonly used timer type in iOS, which allows you to execute a piece of code after a period of time. The accuracy of the NSTimer timer is relatively low because it is not synchronized with the screen refresh frequency, so it may not be applicable in some scenarios where accuracy requirements are relatively high. In addition, the call method of the NSTimer timer is performed through RunLoop, so it is also thread-safe.
The steps to use the NSTimer timer are as follows:
- Create an NSTimer object.
- Set the target and selector of the timer.
- Add NSTimer to RunLoop.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
It should be noted that: NSTimer will hold the target object after being added to RunLoop, which can easily lead to circular reference problems. You need to pay attention to uncirculating references.
GCD timer
GCD timer is a common timer method in iOS, implemented using the functions provided by the Grand Central Dispatch (GCD) framework. Compared with traditional NSTimer and CADisplayLink, GCD timers have higher accuracy and better performance, especially in multi-threaded scenarios.
The implementation principle of GCD timer is to use GCD's dispatch_source_t to create a timer source, and then associate the timer source with the task to be executed. Through the GCD API, the trigger time, number of repetitions and other parameters of the timer can be set, and it can be used easily in a multi-threaded environment.
Here is a sample code for a simple GCD timer:
// Create a GCD timerdispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); // Set the trigger time, interval time and number of repetitions of the timerdispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)); uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC); dispatch_source_set_timer(timer, start, interval, 0); // Set the trigger event of the timerdispatch_source_set_event_handler(timer, ^{ NSLog(@"GCD Timer fired"); }); // Start the timerdispatch_resume(timer);
It should be noted that when using GCD timers, we need to make sure that the timer is stopped at the right time and release the relevant resources. There are two ways to stop Dispatch Timer, one is to use dispatch_source_cancel, and the other is to use dispatch_suspend.
- Use the dispatch_source_cancel function to stop the timer, the example code is as follows:
// Stop the timerdispatch_source_cancel(timer); // Free up resourcestimer = nil;
- Use the dispatch_suspend function to stop the timer. Dispatch_suspend strictly just temporarily suspends Timer. It and dispatch_resume are called balanced. Both will reduce and increase the suspend count of the dispatch object respectively. When this count is greater than 0, Timer will execute.
Another very important note is that the Timer after dispatch_suspend cannot be released! The following code will cause a crash:
- (void)dealloc { dispatch_suspend(timer); timer = nil; // EXC_BAD_INSTRUCTION Crashed}
This is because the dispatch source of GCD will determine whether it is currently in a suspended state when it is released. If it is a suspended state, it needs to be released normally after calling dispatch_resume() to restore it to the active state, otherwise a crash will occur.
Summarize
In this article, we introduce three common timer methods: CADisplayLink, NSTimer, and GCD timer. These timer methods have their advantages and applicable scenarios. CADisplayLink is mainly used for rendering animations, NSTimer is used for periodic execution of tasks, while GCD timer is more flexible and can execute tasks in different threads.
It should be noted that when using these timer methods, we need to avoid some common problems. For example, when using CADisplayLink, you should pay attention to the problem of circular references; when using NSTimer, you should pay attention to the problem of circular references and thread blocking; when using GCD timer, you should pay attention to the life cycle and thread safety of the timer.
In general, we should choose the appropriate timer method according to actual needs and use these methods reasonably to avoid some common problems and ensure the normal operation of the program.
The above is the detailed content of the selection of iOS timers. CADisplayLink NSTimer and GCD. For more information about the selection of iOS timers, please follow my other related articles!