ios – 如何重置NSTimer? SWIFT代码

因此,我正在创建一个应用程序/游戏,您可以在计时器用完之前点击与图片对应的按钮,然后输掉.你得到1秒钟点击按钮,如果你选择了正确的按钮,那么计时器将重置并出现一张新照片.我无法重置计时器.一旦我试图重置它,它会在一秒后触发.这是代码:

loadPicture()运行viewDidLoad()

func loadPicture() {
    //check if repeat picture
    secondInt = randomInt
    randomInt = Int(arc4random_uniform(24))
    if secondInt != randomInt {
        pictureName = String(self.PicList[randomInt])
        image = UIImage(named: pictureName)
        self.picture.image = image
        timer.invalidate()
        resetTimer()

    }
    else{
        loadPicture()
    }
}

这是resetTimer()方法:

func resetTimer(){
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self,selector: Selector("gameOverTimer"),userInfo: nil,repeats: false)

}

我认为它可能与NSRunloops有关?我不确定.我甚至不知道NSRunloop是多么诚实.

解决方法

所以我终于想通了……

我必须通过初始化来创建一个单独的函数来启动计时器.
在resetTimer()函数中,我添加了timer.invalidate()行.所以我的代码看起来像这样:

func loadPicture() {
    //check if repeat picture
    secondInt = randomInt
    randomInt = Int(arc4random_uniform(24))
    if secondInt != randomInt {
        pictureName = String(self.PicList[randomInt])
        image = UIImage(named: pictureName)
        self.picture.image = image
        resetTimer()

    }
    else{
        loadPicture()
    }
}
func startTimer(){
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0,userInfo: "timer",repeats: true)
}

func resetTimer(){

    timer.invalidate()
    startTimer()
}

编辑

使用新的选择器语法,它看起来像这样:

func startTimer(){
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0,selector: #selector(NameOfClass.startTimer),repeats: true)
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...