多线程

iOS GCD之dispatch_group的使用(多个文件并发

2018-06-05  本文已影响155人  彗星来的那一夜
NSMutableArray *imageURLs= [NSMutableArray array];
dispatch_group_t group = dispatch_group_create();                   
for (UIImage *image in images) {
    dispatch_group_enter(group);                                    
    sendPhoto(image, success:^(NSString *url) {
        [imageURLs addObject:url];
        dispatch_group_leave(group);                                 
    });
}
dispatch_group_notify(group, dispatch_get_global_queue(), ^{       
    postFeed(imageURLs, text);
});

首先创建一个dispatch_group
dispatch_group_enter往group中增加一个block任务,dispatch_group_leave则表示该block已经执行完成。需要注意的是,enter和leave必须配对。在这个例子当中,每一个block任务就是上传一张图片。

Calling this function increments the current count of outstanding tasks in the group. Using this function (withdispatch_group_leave
) allows your application to properly manage the task reference count if it explicitly adds and removes tasks from the group by a means other than using the dispatch_group_async
function. A call to this function must be balanced with a call to dispatch_group_leave
. You can use this function to associate a block with more than one group at the same time.
当group中之前所有提交的block任务都执行完后,dispatch_group_notify中的block任务就会被执行。在此例中,所有的图片都上传成功之后,就会发布动态。

上一篇 下一篇

猜你喜欢

热点阅读