原文來自:?https://blog.csdn.net/CC1991_/article/details/81070986
一叹俏、NSTimer的初始化創(chuàng)建
? ? ? ? 1、初始化計時器
?? ?(1)官方API的兩個方法:
?? ?+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
?? ?+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
? ? ? ? 注意:不用scheduled方式初始化的嚷往,需要手動addTimer:forMode: 將timer添加到一個runloop中葛账;而有scheduled的初始化方法將可以默認(rèn)mode直接添加到當(dāng)前的runloop中。
?? ?(2)具體實(shí)例如下所示:
?? ?@property (nonatomic, strong) NSTimer *timer; //聲明計時器屬性
?? ?方法一:
?? ?self.timer = [NSTimer timerWithTimeInterval:5*60 target:self selector:@selector(printNum) userInfo:nil repeats:YES];
? ?? ?[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
?? ?方法二:
?? ?self.timer = [NSTimer scheduledTimerWithTimeInterval:5*60 target:self selector:@selector(printNum) userInfo:nil repeats:YES]; //初始化一個5分鐘執(zhí)行一次的計時器
tableView滑動時皮仁,加入?[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];籍琳,不然,計時器會出現(xiàn)卡頓等其他現(xiàn)象
?NSTimer初始化方法一贷祈,里面沒有scheduled趋急,所以必須要手動addTimer:,將timer添加到runloop中势誊;方法二中有scheduled的初始化方法呜达,將以默認(rèn)的mode把timer添加到當(dāng)前的runloop中。
? ? ? ? 二粟耻、計時器觸發(fā)操作
? ? ? ? 當(dāng)定時器創(chuàng)建完(不用scheduled的)添加到runloop中后查近,該定時器將在初始化時指定的timeInterval秒后自動觸發(fā)眉踱,可以使用-(void)fire;方法來立即觸發(fā)該定時器。
? ? ? ?在重復(fù)執(zhí)行的定時器中調(diào)用這個方法后會立即觸發(fā)該定時器霜威,但不會中斷其之前的執(zhí)行計劃谈喳。在不重復(fù)執(zhí)行的定時器中調(diào)用此方法,立即觸發(fā)后戈泼,就會使這個定時器失效婿禽。
? ? ? ? ?三、計時器停止操作
? ? ? ? ?NSTimer的停止操作只有一種方法可以將timer移除runloop大猛,具體操作如下所示:
? ? ? ? ?[self.timer invalidate]; //停止計時器的方法
? ? ? ? ?self.timer = nil; ? //為了防止意外谈宛,還是要把它賦值為nil的
? ? ? ?由于計時器NSTimer會保留目標(biāo)對象,等到它自身失效時再釋放這個對象胎署。調(diào)用invalidate方法可令計時器失效;執(zhí)行完相關(guān)任務(wù)后窑滞,一次性的計時器也會失效琼牧。如果將計時器設(shè)置成重復(fù)執(zhí)行的模式,那么必須要自己手動調(diào)用invalidate方法哀卫,才能令其停止巨坊。但是由于計時器會保留它的目標(biāo)對象,所以反復(fù)執(zhí)行任務(wù)會導(dǎo)致程序出問題此改,也就是說設(shè)置成重復(fù)執(zhí)行模式的那種計時器趾撵,容易形成“引用循環(huán)”,因此在這種情況下共啃,一定要記得調(diào)用終止計時器的invalidate方法才行占调。
?? ?四、使用計時器需要注意的地方
?? ?1移剪、倒計時的時間間隔(時間單位是秒究珊,可以精確到50-100毫秒);
?? ?2纵苛、指定的執(zhí)行方法剿涮;
?? ?3、實(shí)現(xiàn)指定執(zhí)行方法的對象攻人;
?? ?4取试、是否重復(fù)執(zhí)行;
?? ?5怀吻、使用方法" invalidate "進(jìn)行停止瞬浓;
?? ?6、將對象設(shè)置為" nil “烙博;
?? ?7瑟蜈、特別是在返回到其他視圖控制器的時候烟逊,要在" - (void)viewWillDisappear:
?????(BOOL)animated "方法中(特別注意:不能在" - (void)dealloc”方法中設(shè)置)將timer停止,并設(shè)置為nil铺根。