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

 

文章来自:http://www.cnblogs.com/XYQ-208910/p/4859761.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3