优雅
Each 是一个用 Swift 编写的 NSTimer 桥接库。
let timer = Each(1).seconds // Can be .milliseconds, .seconds, .minute, .hours
timer.perform {
// Do your operations
// This closure has to return a NextStep value
// Return .continue if you want to leave the timer active, otherwise
// return .stop to invalidate it
}
如果您希望将内存管理决策交给 Each
类,可以使用简单的 perform(on: _)
方法。它需要一个 AnyObject
实例。
timer.perform(on: self) {
// Do your operations
// This closure has to return a NextStep value
// Return .continue if you want to leave the timer active, otherwise
// return .stop to invalidate it
}
timer.stop() // This stops immediately the timer
您只能在停止计时器后重新启动计时器。此方法使用相同的执行闭包重新启动计时器。
timer.restart()
不幸的是,接口不能帮助您处理定时器可能创建的内存泄露。在这种情况下,提供了两种解决方案
请参考 用法 部分,使用 perform(on: _)
方法。请注意,使用此方法时,当 owner
被销毁时,不会立即销毁 timer
。它将在 timer
触发下一次并检查 owner
实例是否仍然有效时销毁。
如果您不想声明一个持有所引用的Each
属性,请在方法作用域中创建一个普通的Each
计时器,在每个owner
实例为nil
时返回.stop/true
Each(1).seconds.perform { [weak self] in
guard let _ = self else { return .stop }
print("timer called")
return .continue
}
90%的闭包会以某种方式调用self
,所以这并不那么糟糕
如果第一个解决方案不足以解决问题,您可以声明一个持有所引用的Each
属性,并在释放owner
时调用stop()
函数
final class ViewController: UIViewController {
private let _timer = Each(1).seconds
deinit {
_timer.stop()
}
override func viewDidLoad() {
super.viewDidLoad()
_timer.perform {
// do something and return. you can check here if the `self` instance is nil as for workaround #1
}
}
}
Each遵循MIT许可证发布。请参阅LICENSE文件以获取详细信息。