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

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

你可能感兴趣的:(IOS)