Implementation of timers (NSTimer, DispatchSource, CADisplayLink) and uitableviewnstlink in UITableView in iOS development

Source: Internet
Author: User

Implementation of timers (NSTimer, DispatchSource, CADisplayLink) and uitableviewnstlink in UITableView in iOS development

I have been busy recently, but I am still updating my blog. The content involved in today's blog is not complex. It is a common problem.UITableViewTo summarize the usage of the timer. This blog will show how to useNSTimerOrDispatchSourcerFive common methods. Of course, the first method below is the conventional approach, but it is also a pitfall for using NSTimer in UITableView. The other three methods are to bypass this pitfall solution.

Of course, this blog involvesUITableViewOf course, there should be other implementation methods, but currently I have not involved. You are welcome to provide other implementation methods in the comment area. I will promptly integrate them into the current Demo.

Next, let's summarize the four methods involved in this blog:

  • First, directlyTableViewUse NSTimer on Cell. Of course this method is problematic and will be introduced later.
  • The second is to add NSTimer to the RunLoop corresponding to the current thread.CommonModes.
  • The third is throughDispatchTo implement the timer.
  • The fourth method is to open a new sub-thread, add NSTimer to the RunLoop of the sub-thread, and useDefaultRunLoopModes.
  • The fifth method is to useCADisplayLink.

Below we will introduce the above five implementation methods in detail based on specific examples.

 

 

1. directly use NSTimer in Cell

First, add the corresponding NSTimer directly on the Cell of the UITableView, and useScheduledTimerExecute the corresponding code block. There is nothing special about this method, that is, the direct use of Timer. Below is the code used by our Timer in this part. Of course, it is implemented using Swift, but it is similar to the OC code. The Code is as follows:

  

 

The above code is relatively simple, that is, a timer is added to the Cell, and the time is not updated once every second, and displayed on the Cell timeLabel. The running effect is as follows. From this running effect, we can easily find that when we slide TableView, the timer stops working. The specific reason is that when the RunLoop of the current thread slides in TableViewDefaultModeSwitchedTrackingRunLoopMode. Because Timer is added to RunLoop by default.DefaultModeWhen the Mode is switched, Timer stops running.

However, when the slide is stopped, the Mode is switched back, so Timer can work normally.

  

 

To further look at the Mode switching, we can get the current thread'sRunLoopAnd print the corresponding Mode. The code below is added on the VC corresponding to TableView.ViewDidLoad (), viewDidAppear (), and scrollViewDidScroll () proxy MethodsFor the RunLoop of the current threadCurrentModeThe Code is as follows.

  

  

 

Below is the final running result. From the output results, we can easily see thatViewDidLoad ()TheCurrent ModeIsUIInitializationRunLoopModeFrom the name of this Mode, we can easily find that this Mode is responsible for UI initialization. In the viewDidApperar () method, that is, after the UI is displayed, the RunLoop Mode is switchedKCFRunLoopDefaultMode. Next, we slide TableView and thenScrollViewDidScroll() Print the Mode corresponding to the current RunLoop when sliding in the proxy method. It is not difficult to see from the running results below that when TableView slides, the printed currentModel isUITrackingRunLoopMode. When you stop sliding and Click Show Current Mode to obtain the Current ModeRunLoopDefaultMode. The details are as follows:

 

 

2. Add Timer to CommonMode

The timer in the previous part cannot run normally, becauseNSTimerThe object is added to the current RunLoop by default.DefaultModeSwitchTrackingRunLoopModeThe timer stops working. The most direct way to solve this problem isTrackingRunLoopModeAlso add a copy. In this caseDefaultModeOrTrackingRunLoopModeThe timer will work normally.

If youRunLoopIf you are familiar with it, you can knowCommonModesYesDefaultModeAndTrackingRunLoopModeSo we only needCommonModesThe Code is as follows:

  

 

The difference between the above Code and the first part of the code is that we add the created timer to the current RunLoop.CommonModesIn this way, the timer can also run normally when TableView slides. The final running effect of the above Code is as follows.

  

From this running effect, we can easily find thatTableViewRolling, the timer on the Cell can work normally. However, when we slide the TableView in the upper-right corner, the timer in the first TableView cannot work normally becauseTableViewAll work in the main thread, that is, the RunLoop of these tableviews is the same.

 

 

3. Add the Timer to the DefaultMode under the RunLoop of the sub-thread.

Next, let's look at another solution: to start a new sub-thread, and then add the Timer to the correspondingRunLoop. Of course, it is the RunLoop of the sub-thread. When adding Timer, we can add the Timer to the sub-thread.RunLoopInDefaultMode. Run the RunLoop manually.

Because it is added in the Child threadTimerTimer must work in the Child thread, so we need to update the UI in the main thread. The specific code is as follows:

 

In the above code, we can see that we use a global parallel queue to asynchronously create a Timer object, and then add the object to the asynchronous thread.DefaultRunLoopModeAnd then runRunLoop. Of course, you still need to update the UI in the Child thread in the main thread. Below is the running effect of the above Code. It is not difficult to see from this effect that when slidingTableViewThe timer can work normally.

  

 

 

Iv. DispatchTimerSource

Next, we will not use NSTimer to implement the timer. When talking about GCD in the previous blogDispatchTimerSourceTo implement the timer. Next we willTableViewAddDispatchTimerSourceAnd check the running effect. Of course, the code snippets below are added to the global queue.DispatchTimerSource. Of course, we can alsoMainQueueAddDispatchTimerSource. Of course, we do not recommendMainQueueIn programming, because we try to put some operations that are not very closely related to the main thread into the Child thread. The Code is as follows:

  

 

Next, let's take a look at the running effect of the above Code. From this effect, we can see that the timer can work normally.

  

 

 

V. CADisplayLink

Next we will useCADisplayLinkTo implement the timer function. We have also used the timer function in our previous blog.CADisplayLinkIt is used to calculate FPS. In the code snippet below, we useCADisplayLink.CADisplayLinkCan be added to RunLoop,RunLoopEvery cycleCADisplayLinkThe associated method. When the screen is not stuck1/60 seconds.

The code below corresponds toRunLoopThe timer is not accurate due to blocking. We started a new thread andCADisplayLinkObject added to this subthreadRunLoopAnd then update the UI in the main thread. The Code is as follows:

  

 

We run the above Code. below is the corresponding running result. From the running results below, we can easily see that the timer can run normally during TableView scrolling. Of course, the timer implemented in this method has a high precision.

  

 

After the above five parts, we listed several implementation methods of the timer, through comparison we are not difficult to find its advantages and disadvantages. In the above timer, the accuracy of DispatchSourceTime and CADisplayLink is higher than that of NSTimer. From the code implementation, we can easily see that the accuracy of CADisplayLink is relatively high.

The github address for the Code involved in this blog is:Https://github.com/lizelu/NSTimerWithRunLoop

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.