2016-11-03 7 views
2

Swiftアプリではタイマーを使用しています。私はそれを作成し、それをRunloopに挿入した後、Timerへの参照を保持しないことを好みます。私はそれを無効にしたい。参照を保持しないでこれを行う方法はありますか?RunLoopに配置されたタイマーを無効にするには

答えて

3

タイマセレクタは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") 
     } 
    } 
} 
+0

ああ、華麗です!まさに私が思いついたこと。応援 – dugla

関連する問題