Skip to content

Instantly share code, notes, and snippets.

@keighl
Last active September 1, 2018 17:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keighl/6319942 to your computer and use it in GitHub Desktop.
Save keighl/6319942 to your computer and use it in GitHub Desktop.
SDWebImage in a UITableViewCell - cancel any download operation before reusing the cell. Otherwise, you might see previous images loading in before the correct one is finished downloading.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"MoveViewCell";
CBMoveView *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell)
cell = [[CBMoveView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
cell.move = (CBMove *)[self.moves objectAtIndex:indexPath.row];
[cell configure];
return cell;
}
}
// AFTER
@interface CBMoveCell
@property (weak) id <SDWebImageOperation> imageOperation;
@end
////////////
- (void)prepareForReuse
{
[super prepareForReuse];
if (self.imageOperation)
[self.imageOperation cancel];
self.imageOperation = nil;
}
- (void)configure
{
// some stuff
if (self.move.image)
{
SDWebImageManager *manager = [SDWebImageManager sharedManager];
self.imageOperation = [manager downloadWithURL:[NSURL URLWithString:self.move.image]
options:SDWebImageRetryFailed
progress:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
if (image)
self.moveImageView.image = image;
}];
}
// some other stuff
}
// BEFORE
- (void)configure
{
// some stuff
if (self.move.image)
{
// Download or retrieve the image from the cache via SDWebImage
[self.moveImageView setImageWithURL:[NSURL URLWithString:self.move.image]
placeholderImage:[UIImage imageNamed:@"placeholderImage"]
options:SDWebImageRetryFailed];
}
// some other stuff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment