iOS-延时执行常见的几种方法

本节主要介绍几种我们通常用到的实现延时的方法。

延时方法我们统一调用- (void)delayMethod

- (void)delayMethod
{
    NSLog(@"delayMethodEnd = %@",[NSThread currentThread]);
}

1.performSelector方法

该方法也是在主线程中执行的方法,同NSTimer一样,不会阻塞主线程。

[self performSelector:@selector(delayMethod) withObject:nil afterDelay:2.0];

取消performSelector

[self performSelector:@selector(delayMethod) withObject:nil afterDelay:2.0];

注意:上面的取消方法的参数要和执行action的时候传递的参数保持一致。这种方法用来取消某个特定的延迟方法。

取消performSelector的所有被延迟执行的方法:

[NSObject cancelPreviousPerformRequestsWithTarget:self];

2. NSTimer定时器

NSTimer 是iOS开发工作中经常会使用到,充当着定时器的作用。NSTimer不会阻塞主线程,只是把action滞后,到指定时间由主线程继续执行。

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];

取消延时,定时器对象调用方法:

[timer invalidate];

3. NSThread线程的sleep

此方法是一种阻塞执行方式,建议放在子线程中执行,否则会卡住界面。但有时还是需要阻塞执行,如进入欢迎界面需要沉睡3秒才进入主界面时。

[NSThread sleepForTimeInterval:2.0];

4. GCD

GCD的dispatch_after方法常被用来做延迟执行,与上面的两个相比,它可以在除了主线程之外的线程执行,当然也不会阻塞线程。

    __weak ViewController *weakSelf = self;

    /*延迟执行时间2秒*/
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [weakSelf delayMethod];
    });

Demo下载地址https://github.com/MichaelSSY/DelayTest

猜你喜欢

转载自blog.csdn.net/ssy_1992/article/details/79351613