2014-08-28 64 views
2

以下代码用于我的tableView:cellForRowAtIndexPath方法中。 我使用AFNetworking的setImageWithURLRequest来显示单元格的图像。 但是,有时在我的tableView中的单元格上放置了错误的图像。AFNetworkings setImageWithURLRequest为UITableViewCell显示错误图像

我相信错误是当成功块被触发并且contact对象不再对应于下载的图像时。

// ... 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; 

我该如何解决这个问题,并为正确的单元格显示适当的图像?

回答

0

尝试设置cell.profilePicture.imagenil在您的tableView:cellForRowAtIndexPath:开始出列单元格之后。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 
    cell.profilePicture.image = nil;  

    //the rest of your code. 
} 
1

很可能您没有正确准备您的表格单元以供重用。当图像请求由于重用或网络请求失败而无法到达其UIImageView接收器时,可能会导致您看到旧图像。此外,URL请求可能会出现乱序,导致正确的映像被之前可能延迟的网络请求覆盖。

您需要确保清除profilePicture imageView并取消任何可能导致图像稍后更改的挂起的URL请求。

将在你的子类的UITableViewCell下面的代码:

- (void)prepareForReuse { 
    [self cancelImageRequestOperation]; 
    self.profilePicture.image = nil; 
} 

确保您已导入的UIImageView + AFNetworking类别中您的UITableViewCell:

#import UIImageView+AFNetworking.h