Reputation: 3307
The following code is used in my tableView:cellForRowAtIndexPath
method.
I use AFNetworking's setImageWithURLRequest
to display an image for the cell.
However, sometimes wrong images are placed on the cells in my tableView.
I believe the error is when the success block is fired and the contact
object no longer corresponds to the image that was downloaded.
// ... init/deque ...
/* CAN BE EITHER USER OR CONTACT DETAILS */
id contact = [[self.connections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
if ([contact isKindOfClass:[User class]]) {
[cell configurateCellWithUser:(User *)contact];
if(((User*)contact).avatar_name.length > 0){
[cell.profilePicture setImageWithURLRequest:[self getURLRequestForUser:contact]
placeholderImage:[UIImage imageWithData:((User*)contact).avatar_image]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
cell.profilePicture.image = image;
((User*)contact).avatar_image = UIImageJPEGRepresentation(image, 0.01);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
cell.profilePicture.image = [UIImage imageNamed:@"avatar_contact-card"];
}];
}else {
[cell.profilePicture setImage:[UIImage imageNamed:@"avatar_contact-card"]];
}
} else {
[cell.profilePicture setImage:[UIImage imageNamed:@"avatar_contact-card"]];
[cell configurateCellWithContactDetails:(ContactDetails *)contact];
}
return cell;
How can I fix this and have the appropriate image displayed for the correct cell?
Upvotes: 3
Views: 651
Reputation: 2088
It is likely that you are not properly preparing your table cell for reuse. This may cause you to see old images when image requests fail to reach their UIImageView receiver due to reuse or network request failure. Additionally, it is possible for URL requests to come out of order, causing the correct image to be overwritten by a previous network request that may have been delayed.
You need to make sure that you clear the profilePicture
imageView and cancel any pending URL requests that may cause the image to change later.
Place the following code in your UITableViewCell subclass:
- (void)prepareForReuse {
[self cancelImageRequestOperation];
self.profilePicture.image = nil;
}
Make sure that you have imported the UIImageView+AFNetworking category in your UITableViewCell:
#import UIImageView+AFNetworking.h
Upvotes: 1
Reputation: 398
Try to set cell.profilePicture.image
to nil
at the beginning of your tableView:cellForRowAtIndexPath:
after dequeueing the cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
cell.profilePicture.image = nil;
//the rest of your code.
}
Upvotes: 0