Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble with NSTimer (Swift)

Tags:

swift

nstimer

--EDITED WITH UPDATED INFORMATION--

What I wish to do is call a function named timerFunc once every five seconds using a NSTimer.scheduledTimerWithTimeInterval method, the issue seems is that during runtime, I get the error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-      
[Animation.ViewController timerFunc:]: unrecognized selector sent to instance 0x7fe548d66040'

In the output log. I've been looking up other people's NSTimers to no avail, I see quite a few have the selector as selector: Selector("timerFunc:") instead of selector: Selector("timerFunc") both ways, however, give the error. Another thing is that both the timerFunc function and the NSTimer are inside of viewDidLoad, are there any issues with that? Any insight on the problem is greatly appreciated, thanks for reading.

timerFunc below

func timerFunc(){

    println("Timer")
}

NSTimer below

NSTimer.scheduledTimerWithTimeInterval(
        5.0,
        target: self,
        selector: Selector("timerFunc"),
        userInfo: nil,
        repeats: true)
like image 805
Althonos Avatar asked Sep 14 '14 22:09

Althonos


People also ask

How do you call a timer in Swift?

A Basic timer is declared as such: //declare blank timer variable var timer = Timer() //in a function or viewDidLoad() timer = Timer. scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) //new function @objc func timerAction(){ print(“timer fired!”) }

How do you set a timer in swift 5?

Creating a non-repeating timerlet timer1 = Timer. scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: false) let timer2 = Timer. scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in print("Timer fired!") }

How do you delay in Swift?

To add a delay to your code we need to use GCD . GCD has a built in method called asyncAfter , which will allow us to run code after a given amount of time. In the above code, Before delay will be printed out first and after 2 seconds, Async after 2 seconds will be printed.


1 Answers

My problem with this was the selector was pointing at a private function.

like image 130
Karmie Avatar answered Sep 29 '22 13:09

Karmie