【问题标题】:Updating UITableView - wrong cells and same images更新 UITableView - 错误的单元格和相同的图像
【发布时间】:2023-04-01 14:19:01
【问题描述】:

我有一张带有少量文字的图片表。这个怎么运作: 我有一个模型,它从 Instagram 获取 JSON 响应并将其全部放入字典数组中。 在我的方法 cellForRowAtIndexPath 中,我将单元格的标签设置为 indexpath.row,然后使用 dispatch_async 开始下载图像(从模型中获取 url)。 图像加载完成后,我检查比较当前单元格和当前 indexpath.row 的标签,如果它们相同,则绘制图像。 它工作正常,直到我刷新我的模型。简单地重新加载相同的数据会导致表格出现奇怪的行为 - 它将前三个单元格显示为相同的图像。 我该如何解决?

这是我的单元格方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.tag = indexPath.row;

    if (self.loader.parsedData[indexPath.row] != nil)
    {
        cell.imageView.image = nil;

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
            dispatch_async(queue, ^(void) {

                NSString *url = [self.loader.parsedData[indexPath.row] objectForKey:@"imageLR"];

                if ([self.cache objectForKey:url] != nil)
                {
                    NSData *imageData = [self.cache objectForKey:url];
                    self.tempImage = [[UIImage alloc] initWithData:imageData];
                }

                else
                {

                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
                self.tempImage = [[UIImage alloc] initWithData:imageData];
                [self.cache setObject:imageData forKey:[self.loader.parsedData[indexPath.row] objectForKey:@"imageLR"]];

                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (cell.tag == indexPath.row)
                    {
                        cell.imageView.image = self.tempImage;
                        [cell setNeedsLayout];
                    }

                    });
            });

    cell.textLabel.text = [self.loader.parsedData[indexPath.row] objectForKey:@"id"];
    }

    return cell;
} 

我尝试将 [tableview reloadData] 放在任何地方,但没有帮助。

【问题讨论】:

    标签: ios objective-c ios6


    【解决方案1】:

    我发现了一个问题。 我使用 tableViewController 上的属性来保存下载的数据。 因此,任何时候各种块都可以同时写入它并使用该指针来设置图像。 更新时发生了什么,几个块同时使用它,产生相同的图像。 我已切换到使用本地 NSData 变量,现在效果很好。

    【讨论】:

      猜你喜欢
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多