Search code examples
iosswiftios8nstimer

Cannot stop NSTimer


I know have many question like that on stackoverflow but with me. I still cannot stop my NSTimer. Below is my code:

func setupTimerForRecord(){
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timeStick:"), userInfo: nil, repeats: true)
    })
}

and function stop:

func resetTimmerLabel(){
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.timer?.invalidate()
        self.timer = nil
        self.timeMin = 0
        self.timeSec = 0
        var timeString = String(format: "%02d:%02d", arguments: [self.timeMin, self.timeSec])
        self.lblTimer.text = timeString
    })
}

function selector:

func timeStick(timer: NSTimer){
    print("timeStick")
    self.timeSec++
    if self.timeSec == 60{
        self.timeSec = 0
        self.timeMin++
    }
    var timeString = String(format: "%02d:%02d", arguments: [self.timeMin, self.timeSec])
    lblTimer.text = timeString
}

call setupTimerForRecord at button clicked. and resetTimmerLabel at viewWillDisappear but the function timeStick still run. Please help me

Edit SORRY for my stupid mistake. The problem is I create another new one timer var timer. It must self.timer into the function setupTimerForRecord


Solution

  • I think its because you're creating a duplicate local variable called timer in setupTimerForRecord() . Set it to self.timer instead.

    func setupTimerForRecord(){
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timeStick:"), userInfo: nil, repeats: true)
        })
    }