Timer定时器
预防Timer循环引用,内存泄漏
⚠️在iOS开发过程中,NSTimer 是我们经常要使用的类。但是稍不注意,就会导致内存泄漏,调用profile的Leaks工具时会发现MyViewController退出之后,就会检测到内存泄漏。
fileprivate var myTimer: Timer?
self.myTimer = Timer.scheduledTimer(timeInterval: interval,
target: self,
selector: #selector(myTimerAction),
userInfo: nil,
repeats: true)
Xcode Guide :“ The object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated.“
原来Timer调用scheduledTimer时,会强引用target,导致互相强引用
解决办法:
-(void) viewDidDisappear {
[super viewDidDisappear];
self.myTimer.invalidate()
self.myTimer = nil
}
千万不要将上述代码放到deinit里面,因为循环引用之后MyViewController对象不会释放,deinit将永远不会被调用。你可以重载viewDidDisappear,放到里面去。或者确定不需要定时器时,及时销毁定时器。
iOS10.0+
weak var weakSelf = self
Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block:{(timer: Timer) -> Void in
weakSelf?.doSomething()
})
总结:
- 当调用Apple的API时,需要传递类对象self本身的,我们一定要看清文档,self会不会被保留强引用(MAC时代的被retain)
- 当self被强引用时,像Timer一样,增加类似的一个扩展,或者可以很好的解决问题
- Block模版类,或许可以很优雅的解决你所遇到的问题