OC中代码延迟执行方式

    第一种:

    [UIView animateWithDuration:1 delay:2 options:1 animations:^{

      

    } completion:^(BOOL finished) {

   

    }];

    //不会阻塞线程,animations  block中的代码对于是支持animation的代码,才会有延时效果,对于不支持animation的代码 不会有延时效果。

    

    第二种:

    [NSThread sleepForTimeInterval:3];//阻塞线程,浪费性能 ,一般不推荐用

    

    第三种:最常用,延迟2秒执行:

    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

      });

      //定制了延时执行的任务,不会阻塞线程,效率较高(推荐使用)

    

    第四种:最直接的方法,这种方法的缺点:每次要为延时写一个方法

    [self performSelector:@selector(test) withObject:nil afterDelay:3];//不阻塞线程

    

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

    [[NSOperationQueue mainQueue] addOperationWithBlock:aBlock];这个和调用performSelector: with afterDelay of 0.0f等价

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值