开发者社区> 问答> 正文

UITableVIew 从服务器加载的图片乱了

我有一个TableView的界面,是一个列表页,只有一个Section,每一个Cell里都有一张图片是从服务器异步加载的。
我用ASIHttpRequest去加载图片,在每个Request里已经通过UserInfo带上了这个Cell的NSIndexPath.row,然后回调的时候,就按照这个NSIndexPath去更新Cell的默认占位图片。
但是,我发现刷两下以后,Cell里的图片又乱掉了。。。
貌似我NSIndexPath.row没用一样的。。。有没有人也遇到过一样的问题啊。。。

完整代码太复杂,把涉及到网络的代码贴一下

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// ...

    [self loadImageWithURL:[self.dataSource objectAtIndex:indexPath.row]
                     index:indexPath.row]; // 这是我自己定义的一个方法

// ...
}

- (void)loadImageWithURL:(NSString *)aURL index:(NSInteger)anIndex {
    ASIHTTPRequest *asiRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:aURL]];
    asiRequest.delegate = self;
    asiRequest.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSString stringWithFormat:@"%d", anIndex],
                            @"index",
                            nil];
    asiRequest.requestMethod = @"GET";
    [asiRequest startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest*)request {
    NSInteger index = [[request.userInfo objectForKey:@"index"] intValue];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:
                                [NSIndexPath indexPathForRow:index
                                                   inSection:0]];
    cell.imageView.image = [UIImage imageWithData:request.responseData];
}

展开
收起
a123456678 2016-07-19 15:44:49 1866 0
1 条回答
写回答
取消 提交回答
  • UITableView 对 cell 会有重用机制,以保证较少的内存使用。而带来的问题是,如果代码写得不仔细,可能会导致某行 cell 的内容出现在另一行。

    2019-07-17 19:58:28
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何运维千台以上游戏云服务器 立即下载
网站/服务器取证 实践与挑战 立即下载
ECS块储存产品全面解析 立即下载