猿问

为什么我刷两下以后,Cell里的图片又乱掉了?什么情况啊

我有一个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];}


斯蒂芬大帝
浏览 140回答 2
2回答

精慕HU

UITableView 对 cell 会有重用机制,以保证较少的内存使用。而带来的问题是,如果代码写得不仔细,可能会导致某行 cell 的内容出现在另一行。把 cellForRowAtIndexPath 的完整代码贴出来吧。

慕桂英3389331

这个问题我曾经也遇到过,我的解决方案是:在每一个ImageView的对象中记录该图片的URL,当异步请求回调,要展示图片的时候,先检查URL是否一致,如果不一致,就先把请求下来的图片丢进缓存。
随时随地看视频慕课网APP

相关分类

iOS
我要回答