在此图像上执行某些操作后加载异步图像 - 滚动时图像会更改为错误的图像

时间:2015-12-08 12:07:33

标签: ios swift uitableview

我知道有类似的问题:Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

但我不仅从URL加载图像。我拥有它们,对它们执行一些操作,然后将它们分配到UIImageView WITHIN UITableViewCell

我就是这样做的:

  1. cellForRowAtIndexPath:

    cell.configureCellWithComment(comment)
    
  2. 这些是我单元格内的方法:

    func configureCellWithComment(comment: WLComment) {
    
        if let attachmentUrl = comment.attachmentUrl, let fileName = NSURL(string: attachmentUrl)?.lastPathComponent {
    
            if !NSFileManager.defaultManager().fileExistsAtPath(comment.destinationPathForAttachment().URLByAppendingPathComponent(fileName).path!) {
    
                WLFileClient.sharedClient().downloadFileFrom(attachmentUrl, destinationPath: comment.destinationPathForAttachment(), fileName: fileName, progress: nil, completionBlock: { error in
                    self.attachImageToImageView()
                })
            } else {
                attachImageToImageView()
            }
        }
    }
    
  3. 私人方法:

    private func attachImageToImageView() {
    
        if let attachmentUrl = comment.attachmentUrl, let fileName = NSURL(string: attachmentUrl)?.lastPathComponent {
    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    
                let image = WLFileClient.sharedClient().previewImageForFileAtUrl(self.comment.destinationPathForAttachment().URLByAppendingPathComponent(fileName))
    
                dispatch_async(dispatch_get_main_queue(), {
                    self.previewAttachmentButton.enabled = true
                    self.attachmentPreviewImageView.image = image
                });
            });
        }
    }
    

    我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

您的downloadFileFrom是一种asyc方法。因此,当此任务完成时,该单元可能已被重用于另一行。因此,在调用self.attachImageToImageView()之前,请检查当前单元格是否与方法启动时的行相同。

cellForRowAtIndexPath中,将单元格的标记设置为当前行号。

cell.tag = indexPath.row

现在在configureCellWithComment方法中,首先将标记存储到变量中,然后在异步任务之后检查变量是否仍然相同:

var tagCache:int = self.tag;

WLFileClient.sharedClient().downloadFileFrom(attachmentUrl, destinationPath: comment.destinationPathForAttachment(), fileName: fileName, progress: nil, completionBlock: {

    if(tagCache==self.tag)
      self.attachImageToImageView()
})

PS:我更习惯于Objective-C,而不是swift,所以原谅语法错误(如果有的话)。