一. performSelector
/**
第一個參數(shù):需要延遲執(zhí)行的方法
第二個參數(shù):要傳入的參數(shù)(id類型)
第三個參數(shù):延遲的時間
*/
[self performSelector:@selector(testMethod1:) withObject:@"aaa" afterDelay:5.0];
二. NSTimer
// 1.延遲執(zhí)行某一段代碼
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
// 需要延遲執(zhí)行的代碼
}];
// 2.延遲執(zhí)行某一個方法
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(testMethod1:) userInfo:nil repeats:NO];
// 如果使用上面兩種延遲執(zhí)行的方法,建議將定時器添加到NSRunLoop的Common模式中,防止其他控件的交互影響到定時器
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
// 取消定時器
[timer invalidate];
// 取消的同時要銷毀定時器
timer = nil;
三. NSThread
//該方法使當前線程進入休眠狀態(tài)來達到延遲的目的
// 只有一個參數(shù):延遲的時間
[NSThread sleepForTimeInterval:5.0];
四. GCD
// 第一個參數(shù):延遲的時間
// 可以通過改變隊列來改變線程
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 需要延遲執(zhí)行的代碼
};