尝试在(Xcode 9 和 Swift 4)中异步加载 tableView
中的图像,似乎我有一个正确的方法但是如果我快速滚动 tableView
我的代码停止工作.所以基本上我没有发现错误。
这是我的代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
let feed = feeds[indexPath.row]
cell.titleLabel.text = feed.title
cell.pubDateLabel.text = feed.date
cell.thumbnailImageView.image = nil
if let image = cache.object(forKey: indexPath.row as AnyObject) as? UIImage {
cell.thumbnailImageView?.image = image
} else {
let imageStringURL = feed.imageUrl
guard let url = URL(string: imageStringURL) else { fatalError("there is no correct url") }
URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
if let data = try? Data(contentsOf: url!) {
DispatchQueue.main.async(execute: {
guard let image = UIImage(data: data) else { fatalError("can't create image") }
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell // fast scroll issue line
updateCell.thumbnailImageView.image = image
self.cache.setObject(image, forKey: indexPath.row as AnyObject)
})
}
}).resume()
}
return cell
}
我在线上有问题:
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
如果我慢慢向下滚动,一切正常,不会出现任何错误。
有谁知道我哪里做错了吗?
最佳答案
如果您尝试使用 tableView.cellForRow(at:)
获取的单元格当前不可见,则可能会发生这种情况。
为避免崩溃,您可以将可选值用作:
let updateCell = tableView.cellForRow(at: indexPath) as? CustomTableViewCell // fast scroll issue line
updateCell?.thumbnailImageView.image = image
一切保持原样,我希望它能正常工作,没有任何错误。
关于ios - 如果我快速滚动 tableView,则返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45014389/