iOS開(kāi)發(fā)中方法延遲執(zhí)行的幾種方式
概述
項(xiàng)目開(kāi)發(fā)中經(jīng)常會(huì)用到方法的延時(shí)調(diào)用,下面列舉常用的幾種實(shí)現(xiàn)方式:
1.performSelector
2.NSTimer
3.NSThread線程的sleep
4.GCD
1.performSelector
[self performSelector:@selector(delayMethod) withObject:nil/*可傳任意類型參數(shù)*/ afterDelay:2.0];
此方法是一種非阻塞的執(zhí)行方式绍刮。取消方法:
第一種:
/**
* 取消延遲執(zhí)行
*
* @param aTarget 一般填self
* @param aSelector 延遲執(zhí)行的方法
* @param anArgument 設(shè)置延遲執(zhí)行時(shí)填寫的參數(shù)(必須和上面performSelector方法中的參數(shù)一樣)
*/
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(nullable id)anArgument;
第二種:
//撤回全部申請(qǐng)延遲執(zhí)行的方法
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
上面2種都是類方法温圆,不能用實(shí)例對(duì)象去調(diào)用,只能用NSObject孩革。
eg:
[NSObject cancelPreviousPerformRequestsWithTarget:self];
2.NSTimer定時(shí)器
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
此方法是一種非阻塞的執(zhí)行方式取消執(zhí)行方法:[time invalidate];
3.NSThread線程的sleep
[NSThread sleepForTimeInterval:2.0];
此方法是一種阻塞執(zhí)行方式岁歉,建議放在子線程中執(zhí)行,否則會(huì)卡住界面膝蜈。但有時(shí)還是需要阻塞執(zhí)行锅移,如進(jìn)入歡迎界面需要沉睡3秒才進(jìn)入主界面時(shí)。沒(méi)有找到取消執(zhí)行方式饱搏。
4.GCD
__block ViewController *weakSelf = self;
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^{
[weakSelf delayMethod];
});
此方法可以在參數(shù)中選擇執(zhí)行的線程非剃,是一種非阻塞執(zhí)行方式。因?yàn)樵摲椒ń唤o了GCD自動(dòng)處理推沸,因此不容易取消操作备绽。