iOS开发-GCD 常见用法一(延迟执行)

来源:互联网 发布:网络客服主管计划 编辑:程序博客网 时间:2024/05/22 12:17
一、延迟执行
1.介绍
iOS常见的延时执行有2种方式

(1)调用NSObject的方法

[self performSelector:@selector(run) withObject:nil afterDelay:2.0];

// 2秒后再调用self的run方法

 

(2)使用GCD函数

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    // 2秒后异步执行这里的代码...

});

2.说明

第一种方法,该方法在那个线程调用,那么run就在哪个线程执行(当前线程),通常是主线程。

[self performSelector:@selector(run) withObject:nil afterDelay:3.0];

说明:在3秒钟之后,执行run函数

代码示例:

- (void)viewDidLoad {
    [
superviewDidLoad];
   
// Do any additional setup after loading the view, typically from a nib.
    [
superviewDidLoad];
        
NSLog(@"打印线程----%@",[NSThreadcurrentThread]);
       
//延迟执行
//第一种方法:延迟3秒钟调用run函数
    [
selfperformSelector:@selector(run)withObject:nilafterDelay:5.0];
   
     }
 -(
void)run
 {
        
NSLog(@"延迟执行----%@",[NSThreadcurrentThread]);
     }
// 点击屏幕就触发方法
 -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
 {
        
//在异步函数中执行
        
dispatch_queue_t queue =dispatch_queue_create("wendingding",0);
   
        
dispatch_sync(queue, ^{
                 [
selfperformSelector:@selector(test)withObject:nilafterDelay:5.0];
            });
        
NSLog(@"异步函数");
     }
 -(
void)test
 {
    
NSLog(@"异步函数中延迟执行----%@",[NSThreadcurrentThread]);
    
     }
执行结果



第二种方法,
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

       //延迟执行的方法

    });
在5秒钟之后,执行block中的代码段。

- (void)viewDidLoad {

   
// Do any additional setup after loading the view, typically from a nib.
    [superviewDidLoad];
           NSLog(@"打印当前线程---%@",  [NSThread currentThread]);
   
        
//延迟执行,第二种方式
        
//可以安排其线程(1),主队列
        
dispatch_queue_tqueue=dispatch_get_main_queue();
       
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0*NSEC_PER_SEC)), queue, ^{
               
NSLog(@"主队列--延迟执行------%@",[NSThreadcurrentThread]);
            });

       
//可以安排其线程(2),并发队列
        
//1.获取全局并发队列
        
dispatch_queue_tqueue1=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
        
//2.计算任务执行的时间
        
dispatch_time_twhen=dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0*NSEC_PER_SEC));
        
//3.会在when这个时间点,执行queue中的这个任务
        
dispatch_after(when, queue1, ^{
                
NSLog(@"并发队列-延迟执行------%@",[NSThreadcurrentThread]);
             });

}

执行结果
如果队列是主队列,那么就在主线程执行,如果对列是并发队列,那么就会开启一个新线程,在子线程中执行
1 0
原创粉丝点击