zoukankan      html  css  js  c++  java
  • iOS中延时执行的几种方式的比较和汇总



    转载自:

    http://blog.sina.com.cn/s/blog_8280f5ec0101k03c.html

    http://www.jianshu.com/p/21d351116587

    本文列举了四种延时执行某函数的方法及其一些区别。假如延时1秒时间执行下面的方法。

    - (void)delayMethod { NSLog(@"execute"); }
    


    1.performSelector方法

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


    此方式要求必须在主线程中执行,否则无效。
是一种非阻塞的执行方式,
暂时未找到取消执行的方法。
    2.定时器:NSTimer

    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
    


    此方式要求必须在主线程中执行,否则无效。
是一种非阻塞的执行方式,
可以通过NSTimer类的- (void)invalidate;取消执行。
    3. sleep方式

    [NSThread sleepForTimeInterval:1.0f]; [self delayMethod];
    


    此方式在主线程和子线程中均可执行。
是一种阻塞的执行方式,建方放到子线程中,以免卡住界面
没有找到取消执行的方法。
    4.GCD方式

    double delayInSeconds = 1.0;
     __block ViewController* bself = self;
     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     [bself delayMethod]; });}
    


    此方式在可以在参数中选择执行的线程。
是一种非阻塞的执行方式,
没有找到取消执行的方法。

  • 相关阅读:
    习题解答chapter09
    习题解答chapter08
    习题解答chapter07
    银行账户实验-1.2
    银行账户实验-1.1
    银行账户实验-1.0
    习题解答chapter06
    习题解答chapter05
    习题解答chapter04
    习题解答chapter03
  • 原文地址:https://www.cnblogs.com/superbobo/p/5261615.html
Copyright © 2011-2022 走看看