当我用一个NSTimer调用一个函数时,NSException错误

时间:2015-12-25 10:35:00

标签: swift nstimer

嘿,我试图每1秒调用一次函数,但我不断收到以下错误:

  

以NSException类型的未捕获异常终止

这是我的代码,当我按下按钮时出现错误。

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)

我不知道如何修复此错误:( 任何帮助将不胜感激!!

2 个答案:

答案 0 :(得分:1)

看起来您在错误的范围内定义了该方法。你似乎有像

这样的东西
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)

}

这意味着countDownFunccountDownFunc2功能仅在mySpecialFunc范围内定义并可用。您正在操作的对象/类对它一无所知,因此您的计时器和操作选择器都会失败。你要做的就是将这两种方法移出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"
}

答案 1 :(得分:0)

嘿看this

myButton.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside)
let timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval: 1, target: self, selector: "test", userInfo: nil, repeats: false)
// cit

他没有使用selector: Selector("method name"),他使用selector: "method name"