iOS:GCD技术——仅仅执行一次和执行多次 dispatch_once和dispatch_apply

只执行一次  (多用于单例模式)

dispatch_once(dispatch_once_t *predicate, dispatch_block_t block);

dispatch_once_t *predicate:一个全局的变量      dispatch_block_t block:block函数块

多次执行

dispatch_apply(size_t iterations, dispatch_queue_t queue,void (^block)(size_t));

size_t iterations:执行次数      dispatch_queue_t queue:队列      void (^block)(size_t):block函数块

 

具体举例如下:

1、只执行一次时:

//自定义一个block函数块

//定义block
typedef void (^BLOCK)(void);
    
//将执行代码封装到block中
BLOCK myBlock = ^(){
    static int count = 0;
    NSLog(@"count=%d",count++);
};

//执行dispatch_once函数

//myblock调用
//myBlock();
//myBlock();
        
//只会执行一次,GCD once
static dispatch_once_t predicate;
dispatch_once(&predicate, myBlock);
dispatch_once(&predicate, myBlock);

//运行结果:虽然执行两次,只有一个输出

2015-10-07 22:54:34.279 04-GCD-once[3501:278570] count=0

 

 

2、多次执行时:

//自定义一个block函数

//定义block
typedef void (^BLOCK)(size_t);
    
//将函数封装到block
BLOCK myBlock = ^(size_t size){
    
    static int count = 0;
    NSLog(@"count=%d",count++);
        
};

//执行dispatch_apply

//GCD多次执行任务
dispatch_apply(5, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), myBlock);

//运行结果如下:执行了5次,有5个输出

2015-10-07 22:57:59.438 05-GCD-apply[3528:280053] count=0
2015-10-07 22:57:59.438 05-GCD-apply[3528:280093] count=2
2015-10-07 22:57:59.438 05-GCD-apply[3528:280094] count=3
2015-10-07 22:57:59.438 05-GCD-apply[3528:280095] count=1
2015-10-07 22:57:59.439 05-GCD-apply[3528:280053] count=4

 

posted @ 2015-10-07 22:58  XYQ全哥  阅读(6105)  评论(0编辑  收藏  举报