Swift 3.0: How to solve the problem of timer circular reference

Today, it encapsulates an infinite carousel graph, which is once again trapped in an infinite loop by timer.

This is how timers are created and used in 3.0

fileprivate var cycleTimer : Timer?
cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(anyStrings), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: .commonModes)

Usually we do the same thing with OC in the deinit {} function

 cycleTimer?.invalidate()//remove
 cycleTimer = nil

Don’t think that’s all right. When you pop back to the previous interface, you will find that your timer is still timing, which is not difficult to find. Generally, we will print the timing numbers. So we think that the program doesn’t use the deinit {} function at all, and the two lines of code we wrote won’t be executed

solution:

in the controller using this view, you can destroy the timer before the view enters the background( Does not comply with low coupling)

excellent method:

//cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true)
  weak var weakSelf = self
  cycleTimer = Timer(timeInterval: 1, repeats: true, block: {(timer) in
       weakSelf!.anyString()
   })
  RunLoop.main.add(cycleTimer!, forMode: .commonModes)

After doing this, you must destroy the timer in the deinit{} function, otherwise, your program will crash

 cycleTimer?.invalidate()//remove
 cycleTimer = nil

Similar Posts: