24GHz
24GHz

Reputation: 80

Multiple NSTimers Xcode 6 Swift

So I am increasing the y value of a CGPoint a certain amount per second. To do this I am using an NSTimer that fires at a certain function that increases the y value. The problem is that I am increasing the y value every time the user touches the display. I noticed that every time somebody tapped, there were multiple timers firing, and therefore increasing the y value more than wanted. So how do I remove previous NSTimers and only use the last one?

My current NSTimer setup

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    var timer: NSTimer?
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}

There is more to my code, but this the the basic NSTimer setup that fires at "update" which does the y value increasing.

I tried doing timer.invalidate() but this just made nothing work, and the timer would not restart

Upvotes: 1

Views: 703

Answers (1)

Kiny
Kiny

Reputation: 349

Your problem is every time user taped,you have create a NSTimer instance,and you didn't remove the last `NSTimer instance,so every created instance it run in runloop.

solution 1:

    var timer: NSTimer!
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        if(timer == nil) {
            timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
        }
    }

solution 2:

    var timer: NSTimer!
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        if(timer != nil) {
            timer.invalidate()
            timer = nil
        }
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
    }

By the way: I don't think use NSTimer is a good way to animate object,use core animation instead.

Upvotes: 1

Related Questions