一直對dispatch_group_enter(group)、dispatch_group_leave(group)很陌生,最近看了幾篇博客,整理一下權當理解記憶
Calling this function indicates another block has joined the group through
a means other than dispatch_group_async(). Calls to this function must be
* balanced with dispatch_group_leave().
調用這個方法標志著一個代碼塊被加入了group,和dispatch_group_async功能類似;
需要和dispatch_group_enter()、dispatch_group_leave()成對出現;
void
dispatch_group_enter(dispatch_group_t group);
個人理解:和內存管理的引用計數類似,我們可以認為group也持有一個整形變量(只是假設),當調用enter時計數加1,調用leave時計數減1,當計數為0時會調用dispatch_group_notify并且dispatch_group_wait會停止等待;
以上內容摘自 http://www.lxweimin.com/p/228403206664 作者:liang1991
代碼示例:(取自)http://www.lxweimin.com/p/471469ad9af1 作者:老馬的春天
- (void)test {
NSURL *url = [NSURL URLWithString:@"http://upload-images.jianshu.io/upload_images/1432482-dcc38746f56a89ab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[manager loadImageWithURL:url options:SDWebImageRefreshCached progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
dispatch_group_leave(group);
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"下載完成了");
});
}
enter和leave方法必須成對出現,如果調用leave的次數多于enter就會崩潰,當我們使用SD時,如果Options設置為SDWebImageRefreshCached,那么這個completionBlock至少會調用兩次,首先返回緩存中的圖片。其次在下載完成后再次調用Block,這也就是崩潰的原因。
要想重現上邊方法的崩潰,等圖片下載完之后,再從新調用該方法就行。