Swift中的UIImage内存问题

时间:2015-03-01 17:02:08

标签: ios swift

我遇到了UIImage的问题。每次调用下面的函数时,内存增加5 MB。

我有200张图片,我很害怕它会在我的iPad 2(512 MB)上崩溃所以我添加了分页到我的应用程序 - 每页包含20张图像。

它仍在崩溃。如何减少每页的内存量?

func loadImage(index:Int){
    if self.imgPaths.count == 0 {
        println("Has not data")
        actInd.stopAnimating()
        return
    }
    var imgURL: NSURL = NSURL(string: self.imgPaths[index].stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))!
    let width:CGFloat = self.view.bounds.width
    let height:CGFloat = self.view.bounds.height
    var view:UIView = UIView(frame: CGRectMake(0, 0, width, height));

    if let imgObj = self.dicData[index] {

    }
    else
    {
    println("imgURL \(imgURL)")
    let request: NSURLRequest = NSURLRequest(URL: imgURL)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
        if error == nil {
            let imgItem = UIImage(data: data)!

            var te :Float = self.imgPaths.count > 0 ? Float(index  + 1) / Float(self.imgPaths.count) : 1
            self.progressView.setProgress(te, animated: true)

            if let imgObj = self.dicData[index] {

                if index < self.imgPaths.count - 1
                {
                    var nextIndex:Int = index + 1
                    self.loadImage(nextIndex)
                }
                if(index == self.imgPaths.count - 1)
                {
                    if self.currentImageIndex > 0
                    {
                        self.isAddedFirstImg = true
                    }
                    if !self.isAddedFirstImg
                    {
                        self.scrollViews[0].zoomScale = self.zoomScales[0]
                        self.view.insertSubview(self.scrollViews[0], belowSubview: self.tabBar.viewWithTag(77)!)
                        self.isAddedFirstImg = true
                    }

                    self.actInd.stopAnimating()
                    println("loaded image")
                }
            }
            else
            {
                self.dicData[index] = UIImageView(image: imgItem)

                self.dicData[index]?.frame = CGRect(origin: CGPointMake(0.0, 0.0), size:imgItem.size)

                // 2
                self.scrollViews[index].addSubview(self.dicData[index]!)
                self.scrollViews[index].contentSize = imgItem.size

                // 3
                var doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "scrollViewDoubleTapped:")
                doubleTapRecognizer.numberOfTapsRequired = 2
                doubleTapRecognizer.numberOfTouchesRequired = 1
                self.scrollViews[index].addGestureRecognizer(doubleTapRecognizer)

                var singleTapRecognizer = UITapGestureRecognizer(target: self, action: "scrollViewSingleTapped:")
                singleTapRecognizer.numberOfTapsRequired = 1
                singleTapRecognizer.numberOfTouchesRequired = 1
                self.scrollViews[index].addGestureRecognizer(singleTapRecognizer)

                var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
                swipeRight.direction = UISwipeGestureRecognizerDirection.Right
                self.scrollViews[index].addGestureRecognizer(swipeRight)

                var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
                swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
                self.scrollViews[index].addGestureRecognizer(swipeLeft)

                // 4
                var scrollViewFrame = self.scrollViews[index].frame
                var scaleWidth = scrollViewFrame.size.width / self.scrollViews[index].contentSize.width
                var scaleHeight = scrollViewFrame.size.height / self.scrollViews[index].contentSize.height
                var minScale = min(scaleWidth, scaleHeight)
                self.zoomScales[index] = minScale
                self.scrollViews[index].minimumZoomScale = minScale

                // 5
                self.scrollViews[index].maximumZoomScale = 1.0
                self.scrollViews[index].delegate = self

                // 6
                self.centerScrollViewContents(index)

                dispatch_async(dispatch_get_main_queue(), {
                    println("downloaded image index: \(index) CH.\(self.chapterID)")
                    if(index == 0)
                    {
                        self.scrollViews[0].zoomScale = self.zoomScales[0]
                        self.view.insertSubview(self.scrollViews[0], belowSubview: self.tabBar.viewWithTag(77)!)
                        self.actInd.stopAnimating()
                    }

                    if index < self.imgPaths.count - 1 && !self.stopDownload
                    {
                        var nextIndex:Int = index + 1
                        self.loadImage(nextIndex)
                    }
                    if(index == self.imgPaths.count - 1)
                    {
                        if self.currentImageIndex > 0
                        {
                            self.isAddedFirstImg = true
                        }
                        if !self.isAddedFirstImg
                        {
                            self.scrollViews[0].zoomScale = self.zoomScales[0]
                            self.view.insertSubview(self.scrollViews[0], belowSubview: self.tabBar.viewWithTag(77)!)
                            self.isAddedFirstImg = true
                        }

                        self.actInd.stopAnimating()
                        println("loaded image")
                    }
                })
            }
        }
        else {
            println("Error: \(error.localizedDescription)")
        }
    })
    }
}

2 个答案:

答案 0 :(得分:2)

你的直觉(不是试图同时加载200张高分辨率图像)是对的。

这里有两个问题:

  1. 如果图像尺寸大大超出了您要显示它们的图像视图的尺寸(或者更准确地说,图像视图的尺寸会超过设备scale ),然后你应该resize the image到适合当前图像视图的大小。将大图像加载到小图像视图中仍然需要大量内存。因此,如有必要,请调整图像大小。

  2. 您应该只在内存中保存在任何给定时间可见的图像。滚出视图的那些应该从内存中删除。当前不可见的图像应缓存到某个持久存储中,这样您就可以释放内存,同时能够快速重新检索图像,而无需返回到图像的Web服务。

    您似乎手动将图像视图对象添加到滚动视图中。要使用滚动视图正确执行此操作,需要使用复杂的UIScrollViewDelegate逻辑来确定哪些图像视图可见,并删除滚动视图可见部分之外的视图。使用UITableViewUICollectionViewUIPageViewController会更容易,它们为您提供管理/重用图像视图的机制,因为它们可以滚动进出视图。决定哪一个是合适的取决于所需的UI。但希望这说明了这个想法:不要试图同时在滚动视图中加载所有图像。而不是手动分页自己,考虑使用iOS内置控件之一,这大大简化了这个过程。

  3. 另外,您也可以考虑使用SDWebImageAFNetworking提供的UIImageView类别的图像框架。这些允许一种非常简单的机制,用于从Web服务异步检索图像。您仍然希望使用上述机制之一来管理图像视图,但这两个框架中的任何一个都将简化您的网络代码(延迟加载,异步图像检索,图像缓存,并发图像检索,这将大大改善表演等。)。

答案 1 :(得分:1)

您需要使用Haneke代替NSdata。问题是您的应用下载synchronously,而不是asynchronously

海纳克

imageView.hnk_setImageFromURL(url)

参考:

http://blog.revivalx.com/2015/02/23/uitableview-tutorial-in-swift-using-alamofire-haneke-and-swiftyjson/

https://github.com/Haneke/HanekeSwift