ios - GCD机制在哪里调用?
<p><p>我关注 <a href="http://www.raywenderlich.com/63338/grand-central-dispatch-in-depth-part-2" rel="noreferrer noopener nofollow">RAY WENDERLICH GCD tutorial- part 2</a> ,我不明白:</p>
<p>首次实现</p>
<pre><code> - (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 = ;
break;
case 1:
url = ;
break;
case 2:
url = ;
break;
default:
break;
}
dispatch_group_enter(downloadGroup); // 3
Photo *photo = [ initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
dispatch_group_leave(downloadGroup); // 4
}];
[ addPhoto:photo];
}
dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); // 5
dispatch_async(dispatch_get_main_queue(), ^{ // 6
if (completionBlock) { // 7
completionBlock(error);
}
});
});
}
</code></pre>
<p>第二次实现:</p>
<pre><code> - (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 = ;
break;
case 1:
url = ;
break;
case 2:
url = ;
break;
default:
break;
}
dispatch_group_enter(downloadGroup); // 2
Photo *photo = [ initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
dispatch_group_leave(downloadGroup); // 3
}];
[ addPhoto:photo];
}
dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{ // 4
if (completionBlock) {
completionBlock(error);
}
});
}
</code></pre>
<p>我是第一个实现,相关代码被<code>dispatch_async</code>包围,一切都 super 清晰。</p>
<p>但是,第二个实现还不清楚!我不明白,<code>GCD</code> 机制除了进入和离开通知之外是如何参与的?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>第一个实现从 </p> 开始运行一个后台线程
<pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ // 1
</code></pre>
<p>所以整个函数在那里运行。但是这个后台线程最终在这一行被阻塞(它等待所有照片被下载):</p>
<pre><code> dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER);
</code></pre>
<p>这一切都很好,因为您没有阻塞主线程。但这是一个有点笨拙的实现,因为,</p>
<ul>
<li>你阻塞了一个你确实不需要的线程并且</li>
<li>整个函数周围的 <code>dispatch_async</code> 代码看起来有点难看。</li>
</ul>
<p>所以第二种实现有两个好处:</p>
<ul>
<li>它不是那么“丑陋”并且更具可读性(因为您摆脱了 <code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{}</code>)</li>
<li>并且没有阻塞,因为 <code>dispatch_group_notify</code> 充当异步完成 block 。</li>
</ul></p>
<p style="font-size: 20px;">关于ios - GCD机制在哪里调用?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/25303525/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/25303525/
</a>
</p>
页:
[1]