• GCD调度组、自定义队列来实现多个下载任务


    #define KURL1 @"http://img0.imgtn.bdimg.com/it/u=79920747,2237302485&fm=90&gp=0.jpg"
    #define KURL2 @"http://img5.imgtn.bdimg.com/it/u=2983485216,1361143125&fm=90&gp=0.jpg"
    #import "ViewController.h"
    
    @interface ViewController ()
    {
        dispatch_queue_t myQueue;
    }
    @property (weak, nonatomic) IBOutlet UILabel *remindLabel;
    @property (weak, nonatomic) IBOutlet UIImageView *firstImageView;
    @property (weak, nonatomic) IBOutlet UIImageView *secondImageView;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        //自定义队列
        myQueue=dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
    }
    
    
    - (IBAction)sendBtnClick:(UIButton *)sender
    {
        //创建调度组
        dispatch_group_t myGroup=dispatch_group_create();
        
        //延时执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC*2)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_group_async(myGroup, myQueue, ^{
                
                dispatch_async(myQueue, ^{
                    
                    NSData *firstData=[NSData dataWithContentsOfURL:[NSURL URLWithString:KURL1]];
                    //主队列刷新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        _firstImageView.image=[UIImage imageWithData:firstData];
                        
                    });
                    
                });
            });
            
            dispatch_group_async(myGroup, myQueue, ^{
                
                dispatch_async(myQueue, ^{
                    
                    NSData *secondData=[NSData dataWithContentsOfURL:[NSURL URLWithString:KURL2]];
                    //主队列刷新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        _secondImageView.image=[UIImage imageWithData:secondData];
                        
                    });
                    
                });
                
            });
            
        });
        
        //异步函数监听调度组里面的任务完成后刷新UI
        dispatch_group_notify(myGroup, myQueue, ^{
            _remindLabel.text=@"下载完成";
            
        });
        /*
        //同步函数 主线程阻塞 主要用于数据库操作
        dispatch_group_wait(myGroup, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC)));
         _remindLabel.text=@"下载完成";
         */
    }
  • 相关阅读:
    版本管理系统:svn和git
    Java学习笔记七 常用API对象三
    Java学习笔记六 常用API对象二
    Java学习笔记五 常用API对象一
    Java学习笔记三.3
    Java学习笔记三.2
    Java学习笔记三
    析构函数总结
    C++之类的构造函数,不得不学明白的重点
    C++拷贝构造函数(深拷贝,浅拷贝)
  • 原文地址:https://www.cnblogs.com/thbbsky/p/4376338.html
Copyright © 2020-2023  润新知