iOS shares three ways to develop a timer

  • 2020-11-30 08:35:14
  • OfStack

preface

In development, many times we need to use a timer to refresh a value in real time. That's where the timer comes in. Here, I recommend NSTimer, CADisplayLink, and GCD. I'll show you how to use them in 11. I hope it helps.

1. NSTimer(1 for regular updates 1 for non-interface data)

1. Create methods


NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:) userInfo:nil repeats:NO];

TimerInterval : Time to wait before executing. For example, setting it to 1.0 means that the method executes after 1 second

target : An object that needs to execute a method.

selector : Methods that need to be executed

repeats : Whether a loop is required

2. Release method


[timer invalidate]; 

Note:

After calling the create method, target The counter of the object is incremented by 1 until the execution is complete, automatically decreasing by 1. If it is a loop, it must be closed manually, or the release method may not be executed.

3. The characteristics of

There is delay

Whether it's first order or periodic timer The actual trigger time of the event will be the same as the added time RunLoop and RunLoop Mode Student: Related, if this RunLoop Performing a continuous operation, timer It's going to be delayed. repetitive timer In this case, if the delay exceeds one cycle, it is executed immediately after the end of the delay and continues in the period previously specified.

Must join Runloop

Using the above creation method, will automatically put timer join MainRunloop the NSDefaultRunLoopMode In the. If you create the timer the following way, you must join manually Runloop :


NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

2. CADisplayLink

1. Create methods


self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)]; 
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

2. Stop method


self.displayLink invalidate]; 
self.displayLink = nil;

When putting CADisplayLink object add to runloop In the later, selector Can be called periodically, similar to repeated NSTimer is started; perform invalidate When you operate, the CADisplayLink object will follow runloop Removed, selector The call then stops, similar to NSTimer's invalidate Methods.

3. The characteristics of

Called when the screen is refreshed

CADisplayLink is a timer class that lets us draw specific content onto the screen at a frequency that is synchronized with the screen refresh rate. CADisplayLink is registered in a specific mode runloop At the end of each screen refresh, runloop Will be specified to CADisplayLink target Send the specified one time selector Message corresponding to the CADisplayLink class selector It's going to get called once. So in general, the iOS device screen refresh rate is 60 times per second

delay

The screen refresh frequency of iOS devices is fixed, and CADisplayLink is normally called at the end of each refresh, which is quite accurate. However, if the method being called is time-consuming and exceeds the screen refresh cycle, it will cause several callbacks to be skipped.

If CPU is too busy to guarantee a screen refresh rate of 60 times per second, this results in skipping a number of chances to call the callback method, depending on how busy CPU is.

Usage scenarios

From the principle, it can be seen that CADisplayLink is suitable for continuous repainting of the interface. For example, when playing a video, the next frame needs to be acquired continuously for interface rendering.

4. Important attributes

frameInterval

Value of type NSInteger, used to set the number of frames between calls per call selector Method, the default value is 1, which is called once per frame.

duration

readOnly the CFTimeInterval Value, which represents the time interval between screen refreshes. It is important to note that this property is located in target the selector It is not assigned until it is called for the first time. selector The calculation method of call interval is: call interval = repeats 2 .

3. GCD way

Perform one


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){ 
  // Perform event 
});

repeat


NSTimeInterval period = 1.0; // Set time intervals 
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); // To perform a second 
dispatch_source_set_event_handler(_timer, ^{
  // Execute the event here 
});
dispatch_resume(_timer);

conclusion

GCD, I can only find these materials on the Internet, I am still learning, will update in the future, the above is iOS timer development 3 ways, I hope this article can be helpful to you iOS developers, if you have any questions, you can leave a message to exchange.


Related articles: