带有从iPhone服务器加载的图像的表格视图



嗨,我正在开发IOS应用程序。我的应用程序包含表视图,其中图像是表的一部分。我正在从服务器加载我的图像。它工作正常。但是我的表格视图的问题是,一旦我滚动表格视图,它就会开始闪烁我的图像。这意味着它在一段时间后显示错误的图像一段时间后显示正确的图像。当我滚动时,这种行为会继续。是否需要显式调用任何对象以 nil 或释放某些单元格对象或持有某些单元格对象。我的表格视图单元格如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"MediaContentCell";
MediaContentCell *cell = (MediaContentCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
    cell = (MediaContentCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
VideoDataModel *videoData = [_mediaContentArray objectAtIndex:indexPath.row];
cell.mediaTitle.text = videoData.title;
cell.mediaSubtitle.text = videoData.shortdescription;
NSMutableArray *posters = videoData.poster;
dispatch_queue_t myQueue = dispatch_queue_create("ImageQue",NULL);
dispatch_async(myQueue, ^
{
    UIImage *image;
    if(!posters)
    {
        image = [UIImage imageNamed:@"dummyprog_large1.png"];
    }
    else
    {
        for(int index = 0 ; index < posters.count; index++)
        {
            PosterDataModel *posterData = [posters objectAtIndex:index];
            if([posterData.postertype isEqualToString:POSTER_TYPE_LANDSCAPE])
            {
                 image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:posterData.posterurl]]];
                break;
            }
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^
    {
        cell.mediaPicture.image = image;
    });
});
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}

有人可以帮助我吗?需要一些帮助 谢谢。

使用 - SDWebImage

     [cell.imageView sd_cancelCurrentImageLoad];
     [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                       placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

我正在使用这个框架,它对我来说工作正常。

cell.imageView.image = [UIImage imageWithData:yourDefaultImgUrl];
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imageData = [NSData dataWithContentsOfURL:yourServerImageUrl];      
        if (imageData){
            dispatch_async(dispatch_get_main_queue(), ^{
                 UITableViewCell *updateCell = [tableView cellForRowAtIndexPath:indexPath];          
                 if (updateCell)
                updateCell.imageView.image = [UIImage imageWithData:imageData];
            });
        }
    });

它可以帮助您:)

这是导致问题的重用机制

假设您的表格视图有 1000 个单元格要显示,并且一次在屏幕上可见 5 个单元格,则 iOS 只会在内存中创建 6 个 UITableViewCell 对象。

在你的代码中,图像会从网络异步加载,然后设置为索引路径处属于单元格的 [mediaPicture],但是当你滚动表视图时,由于复用机制,[cell.mediaPicture] 可能不再与索引路径正确关联,下载的图像将被错误设置。

你可以看看这个关于重用机制的问题:

UITableViewCell - 理解"可重用"

而阿莫尔的回答正是您案件的解决方案。

最新更新