如何计时功能添加到一个变量迅速
问题描述:
我试图找出我怎么能写为每15秒将“1”的整数转换为变量的函数。所以每次15秒通行证:myVar的:INT + = 1如何计时功能添加到一个变量迅速
我试图设置一个计时器:
myTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(playFunc), userInfo: nil, repeats: true)
答
嘛,只是通过15.0
而不是1.0
到您的计时器调用是这样的:
myTimer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: #selector(playFunc), userInfo: nil, repeats: true)
既然你在你的类具有可变myVar
地方
var myVar = 0 // or initialize it to whatever you like
你只需要实现playFunc
将由计时器每15秒被称为:
func playFunc() {
self.myVar += 1
}
答
你可以简单地改变这样的:
myTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(playFunc), userInfo: nil, repeats: true)
这样:(更改1.0
到15.0
)
myTimer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: #selector(playFunc), userInfo: nil, repeats: true)
或者你可以这样做:
var timesPlayed = 0
func playFunc() {
timesPlayed += 1
if timesPlayed % 15 == 0 {
myVar += 1
}
}
这样做是每一个运行该功能时,它会尝试看看是否可划分15如果是这样,则意味着该功能已运行15次,这将随后加1到您的变量的时间。