常用的延时执行

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-----");
}

 

posted @ 2016-01-06 21:55  去世的闲人  阅读(309)  评论(0编辑  收藏  举报