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

时间:2016-03-24 08:49:21

标签: objective-c macos nstableview

我希望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;

}

有时,它会成功加载,但有时一个单元格永远不会加载图像,如下图所示: enter image description here

我等了很久,但第三张图片从未加载过。

1 个答案:

答案 0 :(得分:0)

看起来这条线正在返回零。

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

你应该检查图像的值,以确保它不是零,并可能添加一些错误处理。也许是这样的。

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
}