0

我正在用 GCD 加载图像,我遇到了一些奇怪的行为。

当您滚动表格视图时,每张专辑都开始获取艺术品。这NSTableCellView艺术品然后停止。

显然这意味着,在调度之后,变量NSTableCellView不再指向同一个实例,这会导致一次又一次地改变同一个单元格的图像。

我试图通过调用viewAtColumn:row:indexOfObject:调度块来解决这个问题,但它并没有解决问题。

有什么建议么?


代码

- (ITAlbumTableCellView *)makeTableCellViewWithAlbum:(ITLibAlbum *)album {
    ITAlbumTableCellView *cellView = (ITAlbumTableCellView *)[self makeTableCellViewWithIdentifier:kTCVIAlbum];

    // ... Mapping Stuff

    // Set artwork
    if (![self._imageCache objectForKey:album]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSImage *artwork = album.artwork;
            if (!artwork || !artwork.isValid) artwork = [NSImage imageNamed:@"noArtwork"];

            [self._imageCache setObject:artwork forKey:album];

            dispatch_async(dispatch_get_main_queue(), ^{
                NSTableCellView *tcv = [self.tableView viewAtColumn:0 row:[self.tableContent indexOfObject:album] makeIfNecessary:NO];
                tcv.imageView.image = artwork;
            });
        });
    } else {
        cellView.imageView.image = [self._imageCache objectForKey:album];
    }

    return cellView;
}
4

1 回答 1

1

您使用可重用的单元格,因此当单元格隐藏在边界之外时,它可以重用于显示其他数据。快速解决:

 - (ITAlbumTableCellView *)makeTableCellViewWithAlbum:(ITLibAlbum *)album {
ITAlbumTableCellView *cellView = (ITAlbumTableCellView *)[self makeTableCellViewWithIdentifier:kTCVIAlbum];
static int tag = 0;
tag++;
int tagForBlock = tag;
cellView.tag = tag;
if (![self._imageCache objectForKey:album]) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSImage *artwork = album.artwork;
        if (!artwork || !artwork.isValid) artwork = [NSImage imageNamed:@"noArtwork"];

        [self._imageCache setObject:artwork forKey:album];

        dispatch_async(dispatch_get_main_queue(), ^{
            if(tagForBlock != cellView.tag)
                return;
            NSTableCellView *tcv = [self.tableView viewAtColumn:0 row:[self.tableContent indexOfObject:album] makeIfNecessary:NO];
            tcv.imageView.image = artwork;
        });
    });
} else {
    cellView.imageView.image = [self._imageCache objectForKey:album];
}

return cellView;
}
于 2013-09-09T13:23:14.907 回答