星空网 > 软件开发 > 操作系统

iOS之延时执行(睡眠)的几种方法

1. 最直接的方法: 

 

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


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

  缺点:每次要为延时写一个方法。

 

2. 用 NSTread

 

  [NSThread sleepForTimeInterval:0.06];  


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

 

3.用GCD。

  double delayInSeconds = 2.0;    

  dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);    

  dispatch_after(popTime, dispatch_get_main_queue(), ^(void){  

     // code to be executed on the main queue after delay    

  }); 


 

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


 

4.定时器:NSTimer

 

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


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

 

5.使用NSOperationQueue,在应用程序的下一个主循环执行:

  <span style="background-color: rgb(255, 255, 255);"><span style="color:#000000;">[[NSOperationQueue mainQueue]   addOperationWithBlock:aBlock];</span></span>  


  这个和调用performSelector: with afterDelay of 0.0f等价 

 

6.可能是不太好的方法,用animation的completion参数

 

  [UIView animateWithDuration:0.0 delay:5.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{  

    } completion:^(BOOL finished) {

     //do stuff here  

    }];  

 

 





原标题:iOS之延时执行(睡眠)的几种方法

关键词:IOS

IOS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

爆单信号?亚马逊计划在旺季雇佣15万名员工;Prime day2.0你参加了吗?:https://www.ikjzd.com/articles/1579650897639858178
吓退持枪劫匪!智能家居安防出海受宠,外国人:买了才踏实:https://www.ikjzd.com/articles/1579652351578562561
洞察宠物赛道热门选品,击中海外消费者“爱宠”的心!:https://www.ikjzd.com/articles/1579656068314914818
欧美独立站如何利用Snapchat AR滤镜引爆流量,撬动年轻一代消费者?:https://www.ikjzd.com/articles/1579656707714654209
取暖产品又被买爆了?外贸公司如何利用自建站抓住风口经济?:https://www.ikjzd.com/articles/1579658994219442177
德国WEEE最新上传链接:https://www.ikjzd.com/articles/1579663536830095362
皇家游轮航线 皇家邮轮旅游攻略:https://www.vstour.cn/a/408245.html
2017春节旅游攻略有吗:https://www.vstour.cn/a/408246.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流