0

我有一张带有少量文字的图像表。它是如何工作的:我有一个模型,它从 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] 放在任何地方,但它没有帮助。

4

1 回答 1

0

I have found a problem. I have used property on tableViewController to hold downloaded data. So at any time various blocks could write to it at same time and use that pointer for setting images. What happened on update, several blocks used it at the same time, resulting in same images. I have switched to using local NSData variable and it works good now.

于 2013-03-30T11:31:45.953 回答