我拼凑了一个Timer类,将NSTimer与我的所有ViewControllers一起使用,代码如下
item = string.split('\n')
result = {}
for i in item:
# get title item
if i[0] == '[':
name = re.sub(r'(\[|\])', '', item[i])
continue
# ...and put into result dict
if name == '1':
if not 'breakfast' in result:
result['breakfast'] = []
result['breakfast'].push(value)
if name == '2':
if not 'lunch' in result:
result['lunch'] = []
result['lunch'].push(value)
if name == '3':
if not 'dinner' in result:
result['dinner'] = []
result['dinner'].push(value)
然后在每个ViewController中,我可以检查时间进度,然后相应地显示一条消息。问题是当我尝试调用它时
我试过
import Foundation
class Timer {
var timer = NSTimer()
var handler: (Int) -> ()
let duration: Int
var elapsedTime: Int = 0
init(duration: Int, handler: (Int) -> ()) {
self.duration = duration
self.handler = handler
}
func start() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(30,
target: self,
selector: Selector("chkProgress"),
userInfo: nil,
repeats: true)
}
func stop() {
timer.invalidate()
}
@objc func chkProgress() {
self.elapsedTime++
self.handler(elapsedTime)
if self.elapsedTime == self.duration {
self.stop()
}
}
deinit {
self.timer.invalidate()
}
}
结果消息总是一样的告诉我我不能用类型(int,int)调用Timer,这是init中的duration()的设置方式
我做错了什么?
答案 0 :(得分:0)
参数不带int,int。他们采用int和闭包。
您还需要修复您的定时器代码;
class Timer {
var timer = NSTimer()
var handler: (x:Int) -> ()
let duration: Int
var elapsedTime: Int = 0
init(duration: Int, handler: (Int) -> ()) {
self.duration = duration
self.handler = handler
}
func start() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(30,
target: self,
selector: Selector("chkProgress"),
userInfo: nil,
repeats: true)
}
func stop() {
timer.invalidate()
}
@objc func chkProgress() {
self.elapsedTime++
self.handler(x: elapsedTime)
if self.elapsedTime == self.duration {
self.stop()
}
}
deinit {
self.timer.invalidate()
}
}
//定时器的实现
var t = Timer(duration: 30, handler:{ (x:Int) -> Void in
//Do soemthing with x;
});