项目开发中经常会用到方法的延时调用,下面列举现有的几种实现方式:
-
1、performSelector
2、NSTimer
3、sleep
4、GCD
下面对上面的几种进行详细的介绍:
第一个方法 : performSelector
代码:
NSLog(@"延迟之前");
[self performSelector:@selector(performSelectorMa) withObject:self afterDelay:2];
NSLog(@"延迟之后");
- (void)performSelectorMa {
NSLog(@"延迟了");
}
运行结果 :
同理 对于的全部取消的performSelector延迟方法
[NSObject cancelPreviousPerformRequestsWithTarget:self];
取消某个方法的延迟
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(perform) object:nil];
第二个方法:NSTimer
延迟方法
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerAfter) userInfo:nil repeats:NO];
取消延迟
[timer invalidate];//关闭定时器
执行结果 :
第三个方法:sleep
sleep是NSThread 线程里面的方法:但是这个方法会阻塞线程;使用的时候要视情况而定;
代码实现
[NSThread sleepForTimeInterval:2];
执行效果 :
第四个方法:GCD
代码实现 :
/**
DISPATCH_TIME_NOW 延迟从当前时间开始
*/
__weak typeof (self) weakSelf = self;
int64_t time = 3;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf gcdAfter];//防止循环引用
});
运行结果:
以上就是几种延迟方法的使用;