思路:创建一个Timer的分类,添加两个类方法,一个是创建实例的方法(target设置为Timer类对象,传入block);
另一个是timerAction的方法(执行block);
这样另外一个持有timer的对象和timer就没有相互引用,就可以在deinit中执行timer的invalidate方法。
1. 创建Timer的Extension
import Foundation
class Block<T> {
let f : T
init(_ f: T) { self.f = f }
}
extension Timer {
class func app_scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Swift.Void) -> Timer {
if #available(iOS 10.0, *) {
return Timer.scheduledTimer(withTimeInterval: interval, repeats: repeats, block: block)
}
return Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(app_timerAction), userInfo: Block(block), repeats: repeats)
}
@objc class func app_timerAction(_ sender: Timer) {
if let block = sender.userInfo as? Block<(Timer) -> Swift.Void> {
block.f(sender)
}
}
}
2. 使用
var time: Int = 60
var timer: Timer?
func creatTimer() {
timer = Timer.app_scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] (_) in
guard let `self` = self else { return }
self.time -= 1
if self.time == 0 {
print("timer结束")
self.timer?.invalidate()
self.timer = nil
} else {
print("timer执行中 -- \(self.time)s")
}
})
}
deinit {
// deinit中需要将timer释放
timer?.invalidate()
timer = nil
}
网友评论