使用dispatch_group的图片批量下载

由于项目需要,在ViewController里面获取到图片地址数组之后,需要批量下载并在下载完后,返回图片数组和相关信息。

//pics - 图片地址数组
//complete - 完成之后的回调block
+ (void)startDownloadingPics:(NSArray *)pics complete:(void (^)(NSMutableArray * picRatioArray))complete {
    
    NSMutableArray *picsRatio = [[NSMutableArray alloc] init];
    // 合并汇总结果
    dispatch_group_t pics_download_queue = dispatch_group_create();
    
    for (NSString *picUrl in pics) {
        
        dispatch_group_async(pics_download_queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
            UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:picUrl];
            if (!image) {
                image = [self getImageFromURL:picUrl];
            }
            
            PicRatioModel *pModel = [[PicRatioModel alloc] initWithPicUrlString:picUrl];
            
            if (image) {
                pModel.whRatio = image.size.width/image.size.height;
                [[SDImageCache sharedImageCache] storeImage:image forKey:picUrl];
            }
            
             [picsRatio addObject:pModel];
            
        });
        
    }
    dispatch_group_notify(pics_download_queue, dispatch_get_main_queue(), ^{
        // 汇总结果
        if (complete && picsRatio) {
            complete(picsRatio);
        }
    });
}

写完之后,貌似看上去很好,其实,这里埋下了一个bug。
经过debug之后,会出现picsRatio 数组为nil ,当调用 [picsRatio addObject:pModel]; 导致奔溃的现象。

后来经过研究发现,数组picsRatio 是在主线程的,然而代码中
picsRatio的addObject:方法却不在主线程,这样就有问题了,于是在addObject方法调用的时候,在主线程操作:

+ (void)startDownloadingPics:(NSArray *)pics complete:(void (^)(NSMutableArray * picRatioArray))complete {
    
    
    NSMutableArray *picsRatio = [[NSMutableArray alloc] init];
    // 合并汇总结果
    dispatch_group_t pics_download_queue = dispatch_group_create();
    
    for (NSString *picUrl in pics) {
        
        dispatch_group_async(pics_download_queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
            UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:picUrl];
            if (!image) {
                image = [self getImageFromURL:picUrl];
            }
            
            PicRatioModel *pModel = [[PicRatioModel alloc] initWithPicUrlString:picUrl];
            
            if (image) {
                pModel.whRatio = image.size.width/image.size.height;
                [[SDImageCache sharedImageCache] storeImage:image forKey:picUrl];
            }
            //返回到主线程添加数据
            dispatch_async(dispatch_get_main_queue(), ^{
                [picsRatio addObject:pModel];
            });
            
        });
        
    }
    dispatch_group_notify(pics_download_queue, dispatch_get_main_queue(), ^{
        // 汇总结果
        if (complete && picsRatio) {
            complete(picsRatio);
        }
    });
}

不知道我这样解决和思路是不是正确,如果有错误,望大神指出,万分感谢。

你可能感兴趣的:(使用dispatch_group的图片批量下载)