ios - 如果我快速滚动 tableView,则返回 nil

标签 ios swift uitableview asynchronous cell

尝试在(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/

相关文章:

ios - registerClass 错误 Tableview

swift - socket 无法连接到重复内容 UIImageView 错误?

ios - 转换后的 tableview 图像产生 "unexpectedly found nil while unwrapping optional"

arrays - 将 Firestore 数据加载到 TableView Swift 4

iphone - 将第一个单元格设置为在 View 加载时突出显示

ios - 动态创建和定位不同尺寸的 UILabels

ios - 使用 Swift 而不是 Objective C 开始 React Native

ios - iOS 上的 opengl : texture only showed correctly on right upper quarter of the view

iphone - 没有背景图片的 UINavigationBar 样式

ios - 在 iOS 中播放视频失败