但我不仅从URL加载图像。我拥有它们,对它们执行一些操作,然后将它们分配到UIImageView
WITHIN UITableViewCell
。
我就是这样做的:
cellForRowAtIndexPath:
cell.configureCellWithComment(comment)
这些是我单元格内的方法:
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()
}
}
}
私人方法:
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
});
});
}
}
我该怎么做才能解决这个问题?
答案 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,所以原谅语法错误(如果有的话)。