异步更新表单元格图像 [英] Update table cell image asynchronously

查看:125
本文介绍了异步更新表单元格图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从json下载图像链接,然后在表格视图开始创建其单元格后创建图像:

Im downloading the image link from a json and then creating the image once the table view start creating its cells:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellController

            DispatchQueue.main.async(execute: { () -> Void in

                if let url = NSURL(string: self.movies[indexPath.row].image) 
                {

                    if let data = NSData(contentsOf: url as URL)
                    {
                        let imageAux = UIImage((data: data as Data))
                        cell.movieImage.image = imageAux
                        self.tableView.reloadData()

                    }
                }
            })

        cell.name = self.movies[indexPath.row].name
        cell.date = self.movies[indexPath.row].date
        return cell
}

这很好用,但是表格视图变得很慢,不是在渲染而是在滚动.我一直在检查RAM和CPU,两者都确实很低,但是我的网络使用率一直在上升,但是图像已经在单元中,所以这意味着它已经完成了. (对于此测试,我仅针对2部电影调用JSON,因此仅对2部图片进行调用)

And this works fine, but the table view becomes really slow, not at rendering but at scrolling. I keep checking the RAM and CPU and both are really low but my network use keeps rising BUT the images are already on the cell so it means its already done. (For this test im calling the JSON for only 2 movies, so 2 images)

在我开始执行此操作之前,我的总下载量约为200kb(含图片),现在在我停止该项目之前,下载量已超过2MB.

Before i started doing this my total download was about 200kb (with images), now its getting over 2MB before i stop the project.

我做错了什么?

推荐答案

您可能需要为后台活动指定一个单独的队列.在这种情况下,您的繁重网络任务位于:

You'll probably want to designate a separate queue for background activities. In this instance, your heavy network task is in:

NSData(contentsOf: url as URL)

这是冻结" UI的内容.最好的解决方案是定义DispatchQueue.background之类的内容并在其中执行网络调用,然后稍后在主线程上执行UI任务,以免锁定您的显示:

This is what is "freezing" the UI. The best solution would be to define something like DispatchQueue.background and perform the network calls there, while then later performing the UI tasks back on the main thread so as not to lock up your display:

DispatchQueue.background.async(execute: { () -> Void in
    if let url = NSURL(string: self.movies[indexPath.row].image)  {
        //Do this network stuff on the background thread
        if let data = NSData(contentsOf: url as URL) {
            let imageAux = UIImage(data: data as Data)
            //Switch back to the main thread to do the UI stuff
            DispatchQueue.main.async(execute: { () -> Void in
                cell.movieImage.image = imageAux
            })
        }
    }
})

让我知道这是否合理.

这篇关于异步更新表单元格图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆