常用的延时执行

1、 performSelector 一旦定制好延时任务,不会卡住当前线程

//2秒后再调用self的run方法
[self performSelector:@selector(run) withObject:nil afterDelay:2.0];

2、 使用GCD函数

// 该方法中, 会根据传入的队列来决定回掉block在哪个线程中执行
  // 如果传入的是主队列, 那么block会在主线程调用
  // 如果传入的是全局队列, 那么block会在子线程中调用
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{ // 这里传入全局队列会在子线程中执行block,如果传入主队列就会在主线程中执行block
      NSLog(@"3秒之后执行  %@", [NSThread currentThread]);
  });

3、 使用NSTimer

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

- (void)test{
    NSLog(@"---- begin-----");
    [NSThread sleepForTimeInterval:3]; // 它会卡住线程
    NSLog(@"---- end-----");
}

4、 [NSThread sleepForTimeInterval:3]  会卡住线程的,不用

- (void)dely1{
  // 1、延时执行不要用 sleepForTimeInterval(它会卡住线程)
  NSLog(@"---- begin-----");
  [NSThread sleepForTimeInterval:3];
  NSLog(@"---- end-----");
}

 

转载于:https://www.cnblogs.com/XXxiaotaiyang/p/5107575.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值