![](/img/trans.png)
[英]UIView screen freeze when calling dispatch_async(dispatch_get_main_queue())
[英]dispatch_async(dispatch_get_main_queue() is not working on iPad, but working on iPhone
我正在使用SDWebImage庫及其在iPhone上的工作方式。 但是我不知道為什么在iPad中不稱呼它。 我試圖設置斷點,但是它也沒有達到斷點。 我將此方法放在cellForItemAtIndexPath中。
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellIdentifier = @"CustomCollectionViewCell";
CustomCollectionViewCell* cell = (CustomCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
[cell.downloadButton setTag:indexPath.row];
[cell.downloadButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
catalogModel = [catalogArray objectAtIndex:indexPath.item];
cell.cellDescription.text = catalogModel.catalogName;
SDWebImageManager *manager = [SDWebImageManager sharedManager];
NSString *urlStr = catalogModel.imageNameThumbnail;
NSURL *url = [NSURL URLWithString:urlStr];
dispatch_async(dispatch_get_main_queue(), ^{
if ([self.catalogCollectionView.indexPathsForVisibleItems containsObject:indexPath])
{
catalogModel = [catalogArray objectAtIndex:indexPath.item];
[manager downloadImageWithURL:[NSURL URLWithString:catalogModel.imageNameThumbnail] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {}completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL)
{
cell.cellImageView.image = image;
NSLog(@"%@",catalogModel.catalogName);
}];
};
});
return cell;
}
並發圖像加載實現中存在問題。 調用-collectionView: cellForItemAtIndexPath:
,設備將在主隊列上執行代碼。 假設-downloadImageWithURL:options:progress:completed:
方法在后台線程上執行圖像加載並立即返回,我們可以在不使用dispatch_async(dispatch_get_main_queue()...
包裝dispatch_async(dispatch_get_main_queue()...
情況下調用它,否則我們不能保證完成處理程序在主線程上執行線程,因此代碼應如下所示
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellIdentifier = @"CustomCollectionViewCell";
CustomCollectionViewCell* cell = (CustomCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
...
SDWebImageManager *manager = [SDWebImageManager sharedManager];
// methods with completion block usually return instantly
[manager downloadImageWithURL:aURL options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize){} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
// ensure ui is updating on main thread and for visible cell
dispatch_async(dispatch_get_main_queue(), ^{
if ([collectionView.indexPathsForVisibleItems containsObject:indexPath]) {
cell.cellImageView.image = image;
}
});
}];
return cell;
}
iPhone和iPad上的不同結果可以用測試設備技術規格的體系結構差異來解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.