gpt4 book ai didi

ios - GCD机制在哪里调用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:04:17 25 4
gpt4 key购买 nike

我关注 RAY WENDERLICH GCD tutorial- part 2 ,我不明白:

第一次实现

    - (void)downloadPhotosWithCompletionBlock:(BatchPhotoDownloadingCompletionBlock)completionBlock
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ // 1

__block NSError *error;
dispatch_group_t downloadGroup = dispatch_group_create(); // 2

for (NSInteger i = 0; i < 3; i++) {
NSURL *url;
switch (i) {
case 0:
url = [NSURL URLWithString:kOverlyAttachedGirlfriendURLString];
break;
case 1:
url = [NSURL URLWithString:kSuccessKidURLString];
break;
case 2:
url = [NSURL URLWithString:kLotsOfFacesURLString];
break;
default:
break;
}

dispatch_group_enter(downloadGroup); // 3
Photo *photo = [[Photo alloc] initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
dispatch_group_leave(downloadGroup); // 4
}];

[[PhotoManager sharedManager] addPhoto:photo];
}
dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); // 5
dispatch_async(dispatch_get_main_queue(), ^{ // 6
if (completionBlock) { // 7
completionBlock(error);
}
});
});
}

第二次实现:

    - (void)downloadPhotosWithCompletionBlock:(BatchPhotoDownloadingCompletionBlock)completionBlock
{
// 1
__block NSError *error;
dispatch_group_t downloadGroup = dispatch_group_create();

for (NSInteger i = 0; i < 3; i++) {
NSURL *url;
switch (i) {
case 0:
url = [NSURL URLWithString:kOverlyAttachedGirlfriendURLString];
break;
case 1:
url = [NSURL URLWithString:kSuccessKidURLString];
break;
case 2:
url = [NSURL URLWithString:kLotsOfFacesURLString];
break;
default:
break;
}

dispatch_group_enter(downloadGroup); // 2
Photo *photo = [[Photo alloc] initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
dispatch_group_leave(downloadGroup); // 3
}];

[[PhotoManager sharedManager] addPhoto:photo];
}

dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{ // 4
if (completionBlock) {
completionBlock(error);
}
});
}

我的第一个实现相关代码被 dispatch_async 包围,一切都非常清晰。

但是,第二个实现还不清楚!我不明白,GCD 机制是如何处理进入和离开通知之外的任何部分的?

最佳答案

第一个实现从

开始运行一个后台线程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ // 1

所以整个功能都在那里运行。但是这个后台线程最终在这一行被阻塞(它等待所有照片被下载):

 dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER);

这一切都很好,因为您没有阻塞主线程。但它的实现有点笨拙,因为,

  • 你阻塞了一个你真的不需要的线程
  • 代码看起来有点难看,因为整个函数都有 dispatch_async

所以第二个实现有两个好处:

  • 它并没有那么“丑陋”并且更具可读性(因为您摆脱了 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{})
  • 并且没有 block ,因为 dispatch_group_notify 作为异步完成 block 。

关于ios - GCD机制在哪里调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25303525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com