user299648 user299648 - 4 months ago 7
iOS Question

Wrong image is set in my tableview cell sometimes when I scroll on my tableview. How can I fix this?

The wrong image is set in my tableview cell sometimes when I scroll on my tableview. How can I fix this? Below is the relevant code in my

cellForRowAtIndexPath
method.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
UIImage * image = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:self.myURL]]];
dispatch_sync(dispatch_get_main_queue(), ^{
cell.myImageView = image;
});
});
return cell;
}

Answer

First check your cell is nill or not and then set image. Becouse cell is reused on scroll time.

see below code it will help you.

static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil)
   {
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
        UIImage * image = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:self.myURL]]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            cell.myImageView = image;
        });
    });
}
return cell;
Comments