技术贴:3.iOS中的延时执行

作者: Xcode10 | 来源:发表于2016-06-30 12:55 被阅读51次

    延迟执行也叫做延时执行。在iOS中有三种延时执行方式:

    1.调用NSObject的方法

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

    //2S后执行self中的func方法。

    2.使用多线程GCD

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(2.0 * NSEC_PER_SEC),dispatch_get_main_queue(),^ {

              //需要延时2秒后执行的代码

    });

    3.使用定时器NSTimer

    [NSTimer scheduledTimerWithInterval:2.0 target:self selector:@selector(func) userInfo:nil repeats:NO];

    //2s后执行self中的func方法。

    4.使用NSThread的线程睡眠机制同样能够达到相同效果,但是会导致主线程阻塞,所以这里不做推荐。

    [NSThread sleepForTimerInterval:2];

    // 需要执行的代码写在后面

    相关文章

      网友评论

        本文标题:技术贴:3.iOS中的延时执行

        本文链接:https://www.haomeiwen.com/subject/lpaxjttx.html