转自:点击打开链接
延迟执行的几种方式;
- 延迟1秒执行代码
-(void)delayMethod{ NSLog(@"delayMethodEnd"); }
- performSelector方法:
此方式要求必须在主线程中执行,否则无效。[self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
是一种非阻塞的执行方式,暂时未找到取消执行的方法。 - 定时器:NSTimer;
此方式要求必须在主线程中执行,否则无效。[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
是一种非阻塞的执行方式,可以通过NSTimer
类的- (void)invalidate;
取消执行。 - sleep方式;
此方式在主线程和子线程中均执行。[NSThread sleepForTimeInterval:1.0f]; [self delayMethod];
是一种阻塞的执行方式,建议放到子线程中,以避免卡住界面
,没有找到取消执行的方法。 - GCD方式
此方式可以在参数中选择执行的线程。__weak id safeSelf = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [safeSelf delayMethod]; });
是一种非阻塞的执行方式,
没有找到取消执行的方式。