iOS中延迟执行一般有三种方法:performSelector,NSTimer,dispatch_after
一:performSelector
延迟方法:[self performSelector:@selector(startP) withObject:nil afterDelay:3.0];
取消延迟:
方法一:这里需要注意参数需保持一致,否则取消失败
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startP) object:nil];
方法二:可以取消所有的延迟调用
[NSObject cancelPreviousPerformRequestsWithTarget:self ];
可能遇到的问题:cancelPreviousPerformRequestsWithTarget不管用,计时依然执行,这是因为performSelector和cancelPreviousPerformRequestsWithTarget必须在同一个线程中执行才可以
dispatch_async(dispatch_get_main_queue(),^{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startP) object:nil];
//或者
//[NSObject cancelPreviousPerformRequestsWithTarget:self ];
});
二:NSTimer
延迟方法:
self.timer=[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(startP) userInfo:nil repeats:NO];
取消方法:[self.timer invalidate];self.timer=nil;
三:dispatch_after
延迟方法:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//主线程
//要执行的操作//延迟两秒后执行
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(), ^{
//要执行的操作//延迟两秒后执行
});
暂无取消
四:sleepForTimeInterval
[NSThread sleepForTimeInterval:1];
这个方法会阻塞主线程
网友评论