0

I have coded my timer with the idea in mind that when my timer reaches 10, it stops. But for some reason, it doesn't.

import Foundation
import UIKit

class SinglePlayer: UIViewController {
    var timerCount = 0.0
    @IBOutlet weak var timer: UILabel!
    var timerVar = NSTimer()

    func isCounting() {
        timerCount += 0.1
        timer.text = "\(timerCount)"
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if timerCount <= 10.0{
            timerVar = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "isCounting", userInfo: nil, repeats:true)
        } else {
            timerVar.invalidate()
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Noja
  • 3
  • 2
  • Aside from the solution to put the condition check into the `isCounting()` function I suspect that you will never see the full incrementing of the timer when the timer is started that soon in `viewDidLoad()` – vadian Nov 08 '15 at 05:52

1 Answers1

0

You need to put condition in the callback function and not on viewDidLoad which is only called once on the load.

func isCounting() {
    timerCount += 0.1
    timer.text = "\(timerCount)"

    if timerCount >= 10.0 {
        timerVar.invalidate()
    }
}
parveen
  • 1,939
  • 1
  • 17
  • 33