您的位置:首页 > 移动开发 > IOS开发

[iOS]NSTimer 不触发事件的解决

2016-03-16 10:13 337 查看

1.创建NSTimer

使用scheduledTimerWithTimeInterval方法创建的NSTimer会以默认方式加入当前NSRunLoop中

使用 timerWithTimeInterval initWithFireDate 创建需要手动加入一个NSRunLoop中

scheduledTimerWithTimeInterval:invocation:repeats:
scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
timerWithTimeInterval:invocation:repeats:
timerWithTimeInterval:target:selector:userInfo:repeats:
initWithFireDate:interval:target:selector:userInfo:repeats:


2 使用NSTimer

//创建计时器,计时器创建后会自动开始计时
let timer  =  NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: Selector("onTimer:"), userInfo: nil, repeats: true)

timer.fire()  //触发onTimer事件,本次触发不影响计时器计时

timer.invalidate() //停止计时器


在其他线程创建计时器时,不触发onTimer,需要在主线程中创建

dispatch_sync(dispatch_get_main_queue(), { () -> Void in
NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: Selector("onTimer:"), userInfo: nil, repeats: true)
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: