俗稱定時(shí)器。
創(chuàng)建方法根據(jù)功能有不同的創(chuàng)建方式:
//參數(shù)repeats是指定是否循環(huán)執(zhí)行,YES將循環(huán),NO將只執(zhí)行一次。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
//timerWithTimeInterval這兩個(gè)類方法創(chuàng)建出來的對(duì)象如果不用 addTimer: forMode方法手動(dòng)加入主循環(huán)池中,將不會(huì)循環(huán)執(zhí)行。并且如果不手動(dòng)調(diào)用fair,則定時(shí)器不會(huì)啟動(dòng)。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
//scheduledTimerWithTimeInterval這兩個(gè)方法不需要手動(dòng)調(diào)用fair,會(huì)自動(dòng)執(zhí)行,并且自動(dòng)加入主循環(huán)池。
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(nullable id)ui repeats:(BOOL)rep NS_DESIGNATED_INITIALIZER;
NSTimer和RunLoop有關(guān)系?NSTimer為什么要添加到RunLoop中才會(huì)有作用?
NSTimer其實(shí)也是一種資源,如果看過多線程變成指引文檔的話,我們會(huì)發(fā)現(xiàn)所有的source如果要起作用,就得加到runloop中去。同理timer這種資源要想起作用,那肯定也需要加到runloop中才會(huì)又效嘍。如果一個(gè)runloop里面不包含任何資源的話,運(yùn)行該runloop時(shí)會(huì)立馬退出。你可能會(huì)說那我們APP的主線程的runloop我們沒有往其中添加任何資源,為什么它還好好的運(yùn)行。我們不添加,不代表框架沒有添加,如果有興趣的話你可以打印一下main thread的runloop,你會(huì)發(fā)現(xiàn)有很多資源。
Runloop RunTime是我們接觸OC語言的第一步,我們希望在短期內(nèi)好好的了解一下這些C語言機(jī)制。