慢UICollectionView与异步加载 [英] Slow UICollectionView with asynchronous loading

查看:165
本文介绍了慢UICollectionView与异步加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UICollectionView ,加载了iPad的存储图像并将其显示在一个网格,像苹果的照片应用程序。在 UICollectionViewCell 加载缩略图异步:

I have an UICollectionView which loads images of the iPad's memory and displays them in a grid,like Apple's Photos app. The UICollectionViewCell loads thumbnails asynchronously:

 func setImage(img:String){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            //load the image in the background
            let image = UIImage(contentsOfFile: img)
            //when done, assign it to the cell's UIImageView
            dispatch_async(dispatch_get_main_queue(), {
                if let imageView = self.imageView{
                    imageView.image = UIImage(contentsOfFile: img)
                }
            })
        })
    }

然而,在滚动视图滞后,就好像它在等待图像加载,尤其是视网膜图形。细胞和图像约240x180px大。这有什么不对的图像加载高于或需要进行进一步的优化?

However, while scrolling the view lags as if it is waiting for the images to load, especially with Retina graphics. The cells and images are about 240x180px big. Is there anything wrong with the image loading above or further optimisations need to be made?

更新:时间探查结果

UPDATE: Time profiler results

推荐答案

您已经发现你正在加载的再次的UIImage 主队列;固定,这将有助于。

You've already found that you're loading the UIImage again on the main queue; fixing that will help.

的UIImage 延迟加载在大多数情况下,其内部的图像数据。一个技巧是调用它的 CGImage 属性,同时仍然在后台排队迫使它实际创建其内部图像数据,而不是懒洋洋地加载它,当图像视图绘制第一时间:

UIImage lazy loads its internal image data in most cases. One trick is to call its CGImage property while still on the background queue to force it to actually create its internal image data instead of lazily loading it when the image view is drawn the first time:

func setImage(img:String){
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        //load the image in the background
        let image = UIImage(contentsOfFile: img)
        image.CGImage // <- Force UIImage to not lazy load the data
        //when done, assign it to the cell's UIImageView
        dispatch_async(dispatch_get_main_queue(), {
            if let imageView = self.imageView {
                imageView.image = image
            }
        })
   })
}

注意:如果您有很多你可能最终得到一个内存警告很快这样的图像。如果你这样做,这可能不会帮助,因为内存的警告通常会导致的UIImage 再次清除其内部的图像数据,以释放资源。

Note: If you have a lot of images you may end up getting a memory warning fairly quickly doing this. If you do, this probably won't help because the memory warning will typically cause UIImage to clear its internal image data again to free up resources.

这篇关于慢UICollectionView与异步加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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