tableview 加载图像异步但有时某些单元格永远不会加载成功?

tableview load image async but sometimes some cell will never load successfully?

我希望 tableview 异步加载图像,

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
  StickerListItemView *rowView = [tableView makeViewWithIdentifier:StickerTableViewIdentifier
                                                         owner:self];
  if (!rowView) {
    rowView = [[StickerListItemView alloc] initWithFrame:NSMakeRect(0, 0, 460, 300)];
    rowView.identifier = StickerTableViewIdentifier;
    id obj = [self.stickerListArray objectAtIndex:row];
    if ([obj isKindOfClass:[StickerListModel class]]) {
    StickerListModel *listModel = (StickerListModel *)obj;
    rowView.productId = listModel.productId;
    rowView.title = listModel.name;
    rowView.intro = listModel.intro;
    rowView.status = [self hasStickersDownloaded:listModel.productId];
    [rowView setDelegate:self];

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^(void) {
      NSImage *image = [self getPreviewImageWithMd5:listModel.md5OfPrieviewImage];
      //****************************************
      NSLog(@"get image at index %ld",(long)row);
       if (image) {
         dispatch_async(dispatch_get_main_queue(), ^{
         rowView.image = image;
         [rowView setNeedsDisplay:YES];
         //**************************************
         NSLog(@"set image at row %ld",(long)row);
         });
       }
    });
  }
}
return rowView;

}

有的时候会加载成功,有的时候一个cell根本加载不出来,如下图:

我等了很久,但是第三张图片一直没有加载。

这行似乎返回了 nil。

NSImage *image = [self getPreviewImageWithMd5:listModel.md5OfPrieviewImage];

您应该检查 image 的值以确保它不是 nil 并可能添加一些错误处理。也许是这样的。

if (image) {
    dispatch_async(dispatch_get_main_queue(), ^{
        rowView.image = image;
        [rowView setNeedsDisplay:YES];
        NSLog(@"set image at row %ld",(long)row);
     });
} else {
    NSLog(@"Received nil image for row %ld", (long)row);
    //possibly set a placeholder image for this row instead
}