user5716477 user5716477 - 4 years ago 105
Swift Question

NSException errror when i call a function with a NSTimer inside

hey i am trying to call a function every 1 second but i keep getting the following error:

terminating with uncaught exception of type NSException

this is the code i have and i get the error when i press the button.

var startButton : UIButton!
var theTime = 0;
var countDownText = "hello"
var countDownTimer = NSTimer


startButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
startButton.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height/3)
startButton.setTitle("\(countDownText)", forState: UIControlState.Normal)
startButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
startButton.addTarget(self, action: Selector("countDownFunc"), forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(startButton)


func countDownFunc() {

countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc2:"), userInfo: nil, repeats: true)

}

func countDownFunc2(){
theTime++
countDownText = "HELLOOOOOOOOO"

}

print(theTime)


i have no clue how to fix this error :(
any help would be greatly appreciated!!

Answer Source

It looks like you defined the method in the wrong scope. You seem to have something like

func mySpecialFunc() {
    ...
    startButton.addTarget(self, action: Selector("countDownFunc"), forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(startButton)

    func countDownFunc() {
        countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc2:"), userInfo: nil, repeats: true)
    }

    func countDownFunc2(){
        theTime++
        countDownText = "HELLOOOOOOOOO"
    }

    print(theTime)

}

That means that the functions countDownFunc and countDownFunc2 are only defined and available in the scope of mySpecialFunc. The object/class you are operating on does not know anything about it and therefore your timer and action selector both fail. What you have to do is move the two methods out of the body of mySpecialFunc:

func mySpecialFunc() {
    ...
    startButton.addTarget(self, action: Selector("countDownFunc"), forControlEvents: UIControlEvents.TouchUpInside)
    self.view?.addSubview(startButton)

}   

func countDownFunc() {
    countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDownFunc2"), userInfo: nil, repeats: true)
}

func countDownFunc2(){
    theTime++
    countDownText = "HELLOOOOOOOOO"
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download