如何使放置在 RunLoop 上的计时器失效

How do I invalidate to a Timer placed on the RunLoop

在 Swift 应用程序中,我正在使用计时器。我不希望在创建 Timer 并将其插入 Runloop 后保留对 Timer 的引用。我希望能够使它无效。有没有办法在不保留参考的情况下做到这一点?

计时器的选择器可以保留对 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")
        }
    }
}