gpt4 book ai didi

swift - 当我调用内部带有 NSTimer 的函数时出现 NSException 错误

转载 作者:行者123 更新时间:2023-11-30 10:08:42 24 4
gpt4 key购买 nike

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

terminating with uncaught exception of type 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)

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

最佳答案

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

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"
}

关于swift - 当我调用内部带有 NSTimer 的函数时出现 NSException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34462069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com