NSTimer使用注意事項#
存在延遲##
不管是一次性的還是周期性的timer的實際觸發事件的時間,都會與所加入的RunLoop和RunLoop Mode有關,如果此RunLoop正在執行一個連續性的運算,timer就會被延時出發。重復性的timer遇到這種情況,如果延遲超過了一個周期,則會在延時結束后立刻執行,并按照之前指定的周期繼續執行。
同一個timer在重復使用之前必需invalidate##
同一個timer在重復使用之前必需invalidate, 否則會造成之前的timer無法停掉,兩個timer同時存在。導致的現象就是timer同時更新兩次。
不要在dealloc函數中停止并釋放NSTimer##
如果這樣做,會導致對象永遠無法調用dealloc函數,也就是會造成內存泄漏。一個比較合理的解釋是NSTimer的回調方法具有retain屬性,所以不停止它的情況下被引用對象的retainCount無法降為0,導致內存泄漏的死循環。
不用scheduled方式初始化的,需要將timer添加到runloop中##
NSTimer *myTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerFired:) userInfo:nilrepeats:NO];
[[NSRunLoopcurrentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
滑動UIScrollView的時候##
當RunLoop處于UITrackingRunLoopMode模式的時候(滑動UIScrollView的時候),使用
scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
invocation:(NSInvocation *)invocation
repeats:(BOOL)repeats
的類方法創建的Timer,是不會收到響應事件。只有RunLoop切換到Default模式時才可以正常響應。如果希望滑動時也可以響應Timer時間,需要把Timer加到RunLoop并指定模式為NSRunLoopCommonModes。