美文网首页
记录一下GCD的小东西

记录一下GCD的小东西

作者: 燃燃爸爸 | 来源:发表于2017-04-18 15:54 被阅读0次

    子线程搞事情,主线程来显示

    我们都知道把UI相关的事情放在主线程,但是如果当我们要下载一张比较大的图片来显示的话,势必会是一个耗时的操作,如果将其放在主线程操作,那么必然会对主线程造成阻塞,那么我们就需要将它放在子线程中去搞,搞完了再到主线程中去显示UI.这也是我们最常使用GCD的地方了

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSLog(@"我在子线程!开始我的耗时操作吧,我是不会阻塞主线程的");
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"事情搞完了回到主线程做事吧");
            });
        });
    

    队列帮你搞事情

    串行队列

    接下来假设一个场景,在一个详情页中,需要先请求到详情数据,再通过详情数据中的某个参数去请求评论列表,哇!是不是有点炸~
    这个时候我们是不是想做一件事情,先去搞详情数据,等详情数据搞到手了,再去搞评论列表的数据.于是,我们这里可以搞一个串行队列帮我们.因为没有真实数据,所以用图片下载代替说明一下串行队列.

    //图片数据
    static NSString * const picUrlOne = @"http://b.hiphotos.baidu.com/image/pic/item/0823dd54564e925838c205c89982d158ccbf4e26.jpg";
    static NSString * const picUrlTwo = @"http://e.hiphotos.baidu.com/image/pic/item/d1160924ab18972bf05282ece3cd7b899e510aaf.jpg";
    static NSString * const picUrlThree = @"http://c.hiphotos.baidu.com/image/pic/item/58ee3d6d55fbb2fb3943da344a4a20a44623dca8.jpg";
    static NSString * const picUrlFour = @"http://e.hiphotos.baidu.com/image/pic/item/1ad5ad6eddc451da9dd88ecdb3fd5266d01632ed.jpg";
    
    - (void)loadImagesBySerial
    {
        //step one:创建一个串行队列
        dispatch_queue_t serialQueue = dispatch_queue_create("dispatch.serial", DISPATCH_QUEUE_SERIAL);
        //step two:讲我们要做的事情分别加入到队列里面
        [self loadImageByDispatch:serialQueue threadcomplete:^{
            NSLog(@"image1StartDownLoad");
            _imageData1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlOne]]];
        } complete:^{
            _imageOne.image = _imageData1;
            NSLog(@"image1DownLoadOver");
        }];
        
        [self loadImageByDispatch:serialQueue threadcomplete:^{
            NSLog(@"image2StartDownLoad");
            _imageData2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlTwo]]];
        } complete:^{
            _imageTwo.image = _imageData2;
            NSLog(@"image2DownLoadOver");
        }];
        
        [self loadImageByDispatch:serialQueue threadcomplete:^{
            NSLog(@"image3StartDownLoad");
            //故意搞一个延迟,证明当遇到耗时的情况,任务4会等到任务3完成才执行
            [NSThread sleepForTimeInterval:3];
            _imageData3 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlThree]]];
        } complete:^{
            _imageThree.image = _imageData1;
            NSLog(@"image3DownLoadOver");
        }];
        
        [self loadImageByDispatch:serialQueue threadcomplete:^{
            NSLog(@"image4StartDownLoad");
            _imageData4 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlFour]]];
            //step three:任务至此,所有耗时操作都已在子线程完成
        } complete:^{
            _imageFour.image = _imageData1;
            NSLog(@"image4DownLoadOver");
            //step four:当我们最后一个任务完成,即可在主线程搞事情了~我们甚至可以将所有的图片显示放在这个位置,让他们一起显示出来
            /*
            _imageOne.image = _imageData1;
                _imageTwo.image = _imageData2;
                _imageThree.image = _imageData3;
                _imageFour.image = _imageData4;
            */
        }];
    }
    
    - (void)loadImageByDispatch:(dispatch_queue_t)queue threadcomplete:(void(^)())threadComplete complete:(void(^)())complete
    {
        dispatch_async(queue, ^{
            if (threadComplete) {
                threadComplete();
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete();
                }
            });
        });
    }
    

    并行队列

    再来搞个事儿,比如:我们现在有一大堆数据要处理,显然是耗时的,不能去阻塞主线程吧~那好,现在子线程你得帮我搞事情,那么问题来了,我需要在页面显示来自4个不同模块的数据,且这些数据处理都是耗时的,那么并行队列就可以出来搞搞事情了,还是用上面下载图片的例子来说明一下并行队列

    - (void)loadImagesByConcurrent
    {
        //step one:创建一个并行队列
        dispatch_queue_t concurrentQueue = dispatch_queue_create("dispatch_concurrent", DISPATCH_QUEUE_CONCURRENT);
        //step two:开始我们要执行的4个任务
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            NSLog(@"image1StartDownLoad");
            _imageData1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlOne]]];
        } complete:^{
            _imageOne.image = _imageData1;
            NSLog(@"image1DownLoadOver");
        }];
        
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            NSLog(@"image2StartDownLoad");
            _imageData2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlTwo]]];
        } complete:^{
            _imageTwo.image = _imageData2;
            NSLog(@"image2DownLoadOver");
        }];
        
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            NSLog(@"image3StartDownLoad");
            [NSThread sleepForTimeInterval:3];
            _imageData3 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlThree]]];
        } complete:^{
            _imageThree.image = _imageData1;
            NSLog(@"image3DownLoadOver");
        }];
        
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            NSLog(@"image4StartDownLoad");
            _imageData4 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlFour]]];
        } complete:^{
            _imageFour.image = _imageData1;
            NSLog(@"image4DownLoadOver");
        }];
    }
    

    至此,你会发现我们的4个任务是几乎同时开始的,至于期间某个任务有阻塞,我们管不了,最终的哪个先结束我们也不知道所以我们看到的结果也是分别显示的这就有点意思了,如果我们需要拿到所有结果一起来显示,又该咋办呢~~这个时候我们就需要dispatch_group这个东西帮忙了
    还是上面下载图片的例子~

    - (void)groupEnterAndLeave
    {
        //step one:创建一个并行队列
        dispatch_queue_t concurrentQueue = dispatch_queue_create("dispatch.concurrent", DISPATCH_QUEUE_CONCURRENT);
        //step two:再来一个组
        dispatch_group_t concurrentGroup = dispatch_group_create();
        
        /**
        dispatch_group_enter,dispatch_group_leave成对出现~~~
        */
        dispatch_group_enter(concurrentGroup);
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            _imageData1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlOne]]];
            dispatch_group_leave(concurrentGroup);
        } complete:^{
            
        }];
        
        dispatch_group_enter(concurrentGroup);
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            _imageData2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlTwo]]];
            dispatch_group_leave(concurrentGroup);
        } complete:^{
            
        }];
        
        dispatch_group_enter(concurrentGroup);
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            _imageData3 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlThree]]];
            dispatch_group_leave(concurrentGroup);
        } complete:^{
            
        }];
        
        dispatch_group_enter(concurrentGroup);
        [self loadImageByDispatch:concurrentQueue threadcomplete:^{
            _imageData4 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:picUrlFour]]];
            dispatch_group_leave(concurrentGroup);
        } complete:^{
            
        }];
        //step three:所有任务完成,收到通知~
        dispatch_group_notify(concurrentGroup, concurrentQueue, ^{
            NSLog(@"AllTaskOver");
            dispatch_async(dispatch_get_main_queue(), ^{
                _imageOne.image = _imageData1;
                _imageTwo.image = _imageData2;
                _imageThree.image = _imageData3;
                _imageFour.image = _imageData4;
            });
        });
    }
    

    除了单例,还能这样玩

    比如只希望在整个工程的生命周期内,只执行一次某段代码,可以这样玩儿

    static dispatch_once_t once;
        dispatch_once(&once, ^{
           /**
           这里是只想执行一次的代码
           */
        });
    

    延时执行

    /**
    第一个参数表示延时时间,第二个参数是在哪个队列执行
    */
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
            //需要做的延时操作
        });
    

    零零星星写了一些,还有很多没有写,具体在实战中遇到的坑之后再写,暂时就这样.

    相关文章

      网友评论

          本文标题:记录一下GCD的小东西

          本文链接:https://www.haomeiwen.com/subject/rstqzttx.html