在Swift应用程序中,我使用定时器。在创建计时器并将其插入Runloop后,我不喜欢保留对它的引用。我想让它失效。有没有一种方法可以在不保留参考的情况下做到这一点?
定时器的选择器可以保持对Timer
对象的引用。试试这个:
class ViewController: UIViewController {
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
let _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerFired(timer:)), userInfo: nil, repeats: true)
}
// Run the timers for 3 times then invalidate it
func timerFired(timer: Timer) {
if count < 3 {
count += 1
print(count)
} else {
timer.invalidate()
print("Timer invalidated")
}
}
}