在iOS开发中,有时会用到延时执行,下面就开发中会用到的四种延时执行的方法进行简单对比,以期后续可以更好的选择合适的延时方式。
需要延时执行的方法:
- (void)delayMethod {
NSLog(@"execute : %@", [NSDate date]);
}
阻塞式延时
阻塞式延时会阻塞当前线程,为避免卡住用户界面,建议放在子线程执行
NSThread
NSLog(@"start : %@", [NSDate date]);
[NSThread sleepForTimeInterval:3.f];
//[NSThread exit];
[self delayMethod];
非阻塞式延时
performSelector
[self performSelector:@selector(delayMethod) withObject:nil afterDelay:3];
NSLog(@"start : %@", [NSDate date]);
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayMethod) object:nil];
NSTimer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
NSLog(@"start : %@", [NSDate date]);
[timer invalidate];
dispatch_after
NSLog(@"start : %@", [NSDate date]);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self delayMethod];
});
Demo : iOS 中延时执行的四种方法及其比较