延遲3秒執行Delay方法
一.performSelector方法
必須在主線程中執行,否則無效。不阻塞線程
[self performSelector:@selector(Delay) withObject:nil afterDelay:3.0f]; - (void)Delay { NSLog(@"執行"); }
二.NSTimer定時器
必須在主線程中執行,否則無效。不阻塞線程
[NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(Delay) userInfo:nil repeats:NO]; - (void)Delay { NSLog(@"執行"); }
三.sleepForTimeInterval方法
主線程和子線程中均可執行。會阻塞線程,建議到子線程中,以免卡住界面
[NSThread sleepForTimeInterval:3.0f]; [self Delay]; - (void)Delay { NSLog(@"執行"); }
四.GCD方式
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self Delay]; }); - (void)Delay { NSLog(@"執行"); }
作者:CoderZb
鏈接:https://www.jianshu.com/p/df2b6b311ff3
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。