要求:延遲3秒執(zhí)行Delay方法
一.performSelector方法
必須在主線程中執(zhí)行,否則無效。不阻塞線程
[self performSelector:@selector(Delay) withObject:nil afterDelay:3.0f];
- (void)Delay {
NSLog(@"執(zhí)行");
}
二.NSTimer定時(shí)器
必須在主線程中執(zhí)行,否則無效。不阻塞線程
[NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(Delay) userInfo:nil repeats:NO];
- (void)Delay {
NSLog(@"執(zhí)行");
}
三.sleepForTimeInterval方法
主線程和子線程中均可執(zhí)行。會(huì)阻塞線程,建議到子線程中,以免卡住界面
[NSThread sleepForTimeInterval:3.0f];
[self Delay];
- (void)Delay {
NSLog(@"執(zhí)行");
}
四.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(@"執(zhí)行");
}