+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block?
這種創建形式可以把timer西東加入到當前的runloop中,不需要手動開啟。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block?
- (void)addTimer:(NSTimer *)timer forMode:(NSRunLoopMode)mode;
這種創建形式不會自動添加到runloop中,需要我們手動添加到runloop中。
需要注意的是:
每個線程都對應一個Runloop,而主線程的Runloop默認是開啟的,子線程的Runloop默認不是開啟的.通常情況我們的Timer是在主線程中創建的,但是也不乏有的時候是在子線程中創建的。在子線程創建Timer需要加入Runloop后,需要我們手動開啟Runloop。
[[NSRunLoopcurrentRunLoop]run];
用target的形式創建timer會出現釋放timer。
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
出現上邊的問題是什么原因呢?
Creates and returns a new NSTimer object and schedules it on the current run loop in the default mode.
After ti seconds have elapsed, the timer fires, sending the message aSelector to target.
repeats
If YES, the timer will repeatedly reschedule it self until invalidated. If NO, the timer will be invalidated after it fires.
上邊的是蘋果給的解釋,把創建的timer加入了當前的runloop中,即當前的runloop對target進行了強引用。而timer又對target進行了強引用。這導致來返回上個界面,target惡婦啊釋放。因此必須手動停掉。