Swift Timer循环引用问题

2,531 阅读5分钟
小时光
我的博客

1、Timer产生循环引用的原因

iOS 10之前使用Timer会因为循环引用造成持有TimerController释放不掉,从而导致内存泄漏。iOS 10之后系统优化了这个问题。一般在iOS 10之前使用Timer的代码如下:

var time: Timer?

override func viewDidLoad() {
     super.viewDidLoad()
     time = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timePrint), userInfo: nil, repeats: true)
}
func timePrint() {
    // do something...
}

deinit {
    print("deinit---------------------11111")
    time?.invalidate()
    time = nil
}

当我在Controller中使用了Timer之后,这个Controllerpopdismiss之后,其内存并不会释放,可以看到计时器也在正常运行,那么这是由于什么原因造成的呢?

1.1、不仅仅是强引用问题

一般情况下,两个实例对象之前相互强引用会造成循环引用,那么按照理解,TimerController之间的引用关系可能是这样的:

Timer001.png

针对这种两者之间的强引用造成的循环引用,只要让其中一个为弱引用就可以解决问题,那么就来试试吧。

修改time为弱引用

weak var time: Timer?

再次运行代码,这时理想中他们之间的引用关系如下图所示,当Controller被释放时,因为是弱引用的关系此时Timer的内存也会被释放:

Timer002.png

再次运行代码,发现并没有如我所愿,当Controller被释放Timer依旧能够正常运行,所以他们的内存还是没有有效释放。为什么我使用了弱引用其内存还是没有释放掉呢?

1.2、TimerRunLoop之间的强引用

这里忽略了一个问题,TimerRunLoop之间的关系,当Timer在创建之后会被当前线程的RunLoop进行一个强引用,如果这个对象是在主线程中创建的,那么就由主线程持有Timer。当我使用了弱引用后他们之间的引用关系是:

Timer003.png

虽然使用了弱引用,但是由于主线程中的RunLoop是常驻内存同时对Timer的强引用,Timer同时又对Controller强引用,这个Controller间接的被RunLoop间接的强引用。即使这个Controllerpopdismiss,因为强引用的关系这部分内存也不能正常释放,这就会造成内存泄漏,并且可能会造成整个App Crash。当Controllerpopdismiss时,他们在内存中的引用关系是:

Timer004.png

关于Timer使用Tatget方式会产生循环引用的原因,国内搜到的一些博客认为是: ViewController、Timer、Tatget三者之间形成了一个相互强引用闭环造成的,但我在看了官方文档Using Timers: References to Timers and Object Lifetimes后,个人并不认同这个观点,当然如果您有其他观点请指出并说明理由。官方文档的原文是:

Because the run loop maintains the timer, from the perspective of object lifetimes there’s typically no need to keep a reference to a timer after you’ve scheduled it. (Because the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method.) In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can stop it whenever appropriate. If you create an unscheduled timer (see Unscheduled Timers), then you must maintain a strong reference to the timer so that it is not deallocated before you use it.

A timer maintains a strong reference to its target. This means that as long as a timer remains valid, its target will not be deallocated. As a corollary, this means that it does not make sense for a timer’s target to try to invalidate the timer in its dealloc method—the dealloc method will not be invoked as long as the timer is valid.

2、How to solve it ?

知道了造成Timer造成循环引用的原因,那么该如何解决Timer造成的循环引用问题呢?

2.1、使用系统提供Block方法

iOS 10之后,系统已经优化了这个问题,如果是iOS 10之后的版本,完全可以使用系统提供的Block回调方式:

if #available(iOS 10.0, *) {
      /// iOS 10之后采用`Block`方式解决Timer 循环引用问题
      time = Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { [weak self] (timer) in
            guard let `self` = self else { return }
            self.timePrint()
      })
}

事实上现在开发一款新的App时可以不考虑iOS 10以下的兼容处理,因为苹果官方统计的数据:Apple Developer: iOS and iPadOS Usage。截止2021年4月10号,只有**8%**的iPhone用户还在使用iOS 13以下的版本,就连微信这种达亿级用户的App都只支持iOS 11以后版本。当然对于一些比较老的App要支持iOS 10之前的系统或者你有一个爱抬杠的产品经理,那么只能做老系统的兼容处理。

2.2、使用GCD提供的DispatchSource替换Timer
var source: DispatchSourceTimer?

source = DispatchSource.makeTimerSource(flags: [], queue: .global())
source.schedule(deadline: .now(), repeating: 2)
source.setEventHandler {
    // do something...
}
source.resume()

deinit {
     source?.cancel()
     source = nil
}
2.3、模仿系统提供的closure

对系统的Timer做扩展处理:

extension Timer {
    class func rp_scheduledTimer(timeInterval ti: TimeInterval, repeats yesOrNo: Bool, closure: @escaping (Timer) -> Void) -> Timer {
        return self.scheduledTimer(timeInterval: ti, target: self, selector: #selector(RP_TimerHandle(timer:)), userInfo: closure, repeats: yesOrNo)
}
    
    @objc class func RP_TimerHandle(timer: Timer) {
        var handleClosure = { }
        handleClosure = timer.userInfo as! () -> ()
        handleClosure()
    }
}

调用方法:

if #available(iOS 10.0, *) {
      /// iOS 10之后采用`Block`方式解决Timer 循环引用问题
      time = Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { [weak self] (timer) in
            guard let `self` = self else { return }
            self.timePrint()
      })
} else {
      /// iOS 10之前的解决方案: 模仿系统的`closure` 解决Timer循环引用问题
      time = Timer.rp_scheduledTimer(timeInterval: 2, repeats: true, closure: { [weak self] (timer) in
            guard let `self` = self else { return }
            self.timePrint()
      })
}
        
func timePrint() {
     // de something...
}
    
deinit {
    time?.invalidate()
    time = nil 
}
2.4、其他解决方法
  • 使用Runtime给对象添加消息处理的方法
  • 使用NSProxy类作为中间对象

本文主要分析了在开发中使用Timer造成循环引用的原因和一些常用的解决方案。