很多时候在Viewcontroller直接用属性引用Timer会造成引用循环(timer会对target/vc进行强引用,vc对timer强引用),下面的方式可以用Block的形式解除引用循环,避免内存泄漏。
// 破除timer引用循环
public typealias TimerExcuteClosure = @convention(block) () -> ()
extension Timer {
private class TimerActionBlockWrapper : NSObject {
var block : TimerExcuteClosure
init(block: @escaping TimerExcuteClosure) {
self.block = block
}
}
public class func safe_scheduledTimerWithTimeInterval(_ ti:TimeInterval, closure: @escaping TimerExcuteClosure, repeats yesOrNo: Bool) -> Timer {
return self.scheduledTimer(timeInterval: ti, target: self, selector: #selector(Timer.excuteTimerClosure(_:)), userInfo: TimerActionBlockWrapper(block: closure), repeats: true)
}
@objc private class func excuteTimerClosure(_ timer: Timer) {
if let action = timer.userInfo as? TimerActionBlockWrapper {
action.block()
}
}
}