title: Faster way to load Images in Collection View
body: <p>I have a little flow problem with my UICollectionView. I want to display PDF's thumbnails just like in Apple's iBook app, when I scroll my collection view I can see it's not really smooth. Here is the way I use to load my pictures :</p>
  
  <pre><code>- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:    (NSIndexPath *)indexPath
  {
       GridCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"gridCell" forIndexPath:indexPath];
  
      ...
  
      // Set Thumbnail
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          if ([Tools checkIfLocalFileExist:cell.pdfDoc])
          {
              UIImage *thumbnail = [Tools generateThumbnailForFile:((PDFDocument *)[self.pdfList objectAtIndex:indexPath.row]).title];
  
              dispatch_async( dispatch_get_main_queue(), ^{
                  [cell.imageView setImage:thumbnail];
              });
          }
      });
  
      ...
  
      return cell;
  }
  </code></pre>
  
  <p>Method to get thumbnail :</p>
  
  <pre><code>+ (UIImage *)generateThumbnailForFile:(NSString *) fileName
  {
      // ----- Check if thumbnail already exist
      NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  
      NSString* thumbnailAddress = [documentsPath stringByAppendingPathComponent:[[fileName stringByDeletingPathExtension] stringByAppendingString:@".png"]];
      BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:thumbnailAddress];
  
      if (fileExists)
          return [UIImage imageWithContentsOfFile:thumbnailAddress];
  
      // ----- Generate Thumbnail
      NSString* filePath = [documentsPath stringByAppendingPathComponent:fileName];
  
      CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:filePath];
      CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL(url);
      CGPDFPageRef pageRef = CGPDFDocumentGetPage(documentRef, 1);
      CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);
  
      UIGraphicsBeginImageContext(pageRect.size);
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextTranslateCTM(context, CGRectGetMinX(pageRect),CGRectGetMaxY(pageRect));
      CGContextScaleCTM(context, 1, -1);
      CGContextTranslateCTM(context, -(pageRect.origin.x), -(pageRect.origin.y));
      CGContextDrawPDFPage(context, pageRef);
  
      // ----- Save Image
      UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
      NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(finalImage)];
      [imageData writeToFile:thumbnailAddress atomically:YES];
      UIGraphicsEndImageContext();
  
      return finalImage;    
  }
  </code></pre>
  
  <p>Do you have any suggestion ?</p>