title: Objective C - UITableViewCell loading image asynchronously
body: <p>I am displaying a table. Each row has an image icon, loaded from an URL. </p>
  
  <p>Since downloading images synchronously blocks the UI, I've implemented am asynchronous way via grand central dispatch.</p>
  
  <p>My problem is that when I scroll down and up, since cells are being re-used, the incorrect images show up. </p>
  
  <p>I can guess why this is happening - it's because the re-used cells update the image and therefore, previous cells will now have the newly downloaded, and wrong, image. What would be an ideal way to resolve this?</p>
  
  <p>Here's my code.</p>
  
  <p>For each image downloaded, I'm storing it in a singleton class called "ImageStore".</p>
  
  <pre><code>// set the data for each cell - reusing the cell
  - (UITableViewCell *)tableView:(UITableView *)tableView
           cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
  
     if (!cell) {
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                        reuseIdentifier:@"UITableViewCell"];
      }
  
      // setting the image for each cell
      // first check if there is UIImage in the ImageStore already
      NSString *imageUrl = [obj objectForKey:@"image"];
      if (imageUrl) {
        if ([[ImageStore sharedStore] imageForKey:imageUrl]) {
  
          [[[tableView cellForRowAtIndexPath:indexPath] imageView] setImage:[[ImageStore sharedStore] imageForKey:imageUrl]];
        } else {
  
          dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
      dispatch_async(queue, ^{
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
        [NSURL URLWithString:[obj objectForKey:@"image"]]]];
        dispatch_sync(dispatch_get_main_queue(), ^{
          [[ImageStore sharedStore]setImage:image forKey:imageUrl];
          [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationNone];
  
              [[[tableView cellForRowAtIndexPath:indexPath] imageView] setImage:image];
        });
      });
        }
      }
      return cell;
  }
  </code></pre>