1

我想在圖像處理每個圖像後加載太多圖像。
但當我上下滾動,懶加載..
這是我的代碼如下。使用dispatch_sync在uicollectionview上延遲加載

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
UICollectionViewCell *cell; 
cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FaceImageCell" forIndexPath:indexPath]; 
UIImageView *fImageView = (UIImageView*)[cell viewWithTag:1]; 
[faceImageView setImage:[UIImage imageNamed:@"ic_loading"]]; 
NSLog(@"Loaded Image row : %d", indexPath.row); 

ALAsset *asset; 
    asset = [_imageList objectAtIndex:indexPath.row]; 
    dispatch_async(all_f_d_queue, ^{ 
     ALAssetRepresentation *representation = [asset defaultRepresentation]; 
     NSString *filename = [representation filename]; 
     NSLog(@"%@", filename); 
     UIImage *image, *fullImage; 
     if ((fullImage = [_fullImageCache objectForKey:filename]) == nil) { 
      image = [UIImage imageWithCGImage:[asset thumbnail] 
              scale:[representation scale] 
             orientation:(UIImageOrientation)[representation orientation]]; 
      vector<cv::Rect> f = [ImageUtils findFeature:image minsize:MIN_FACE_SIZE 
               withCascade:face_cascade]; 

      Mat imageMat = [ImageUtils cvMatFromUIImage:image]; 
      fullImage = [ImageUtils UIImageFromCVMat:imageMat]; 
      [_fullImageCache setObject:fullImage forKey:filename]; 
     } 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [fImageView setImage:fullImage]; 
      [cell setNeedsDisplay]; 
     }); 
    }); 
return cell; 
} 

由於隊列很多,所以發生延遲加載。
我想在加載單元格不可見時停止或取消調度隊列。
我應該如何檢測細胞不可見並停止調度隊列?
請讓我知道。
我可以在android中使用asynctask。但我不知道如何在iOS中實現。

回答

1

你可以使用NSOperation和NSOperationQueue。 它與dispatchlib幾乎相同,但是面向對象。 你可以將工作包裝在NSOperation上,然後將其添加到NSOperationQueue中。 然後你可以隨時取消NSOperation。 可能必須閱讀Apple文檔以更好地解釋這兩個類。

+0

謝謝。還有一件事,我如何檢測細胞是不可見的? – nao0811ta

+0

有一個UICollectionViewDelegate方法 - collectionView:didEndDisplayingCell:forItemAtIndexPath: 但是,如果我必須這樣做,我寧願只取消一個單元格操作,如果有一個在collectionView:cellForItem上啓動一個新單元之前。 – riadhluke

+0

嘿,你知道嗎,有一個wwdc 2012視頻可以處理tableView上的延遲加載。我發現這非常有幫助: 在iOS上構建併發用戶界面 https://daw.apple.com/cgi-bin/WebObjects/DSAuthWeb.woa/wa/login?path=%2F%2Fvideos%2Fwwdc%2F2012%2Findex .php%3Fid%3D211&appIdKey = 891bd3417a7776362562d2197f89480a8547b108fd934911bcbea0110d07f757 – riadhluke

1

看看this tutorial。它顯示瞭如何使用NSOperationQueue異步下載數據,如果用戶滾動並且該單元格不再可見,則取消該隊列。

+0

你是指隊列而不是女王? :) – kelin