iOS Memory Warnings

血红的双手。 提交于 2020-01-11 14:11:35

问题


I'm trying to populate a collection view with images downloaded from a Parse database, but I'm receiving memory warnings followed by occasional crashes. Does anyone know how other apps manage to present so many images without crashing? Can someone show me how to optimize what I already have? Here's all the relevant code: https://gist.github.com/sungjp/99ae82dca625f0d73730

var imageCache : NSCache = NSCache()


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    self.imageCache.removeAllObjects()
}


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    //In storyboard, my collection view cell has the identifier "PostCell"    
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PostCell", forIndexPath: indexPath) as! CollectionViewCell

    //I have an array called "posts" that's filled with PFObjects that have UIImage data
    let postings: PFObject = posts[indexPath.row]

    //setting my cell's string property called "objectId" to the PFObject's ID for the purpose of caching shown below
    cell.objectId = postings.objectId! as String

    let theImage: AnyObject = postings["imageFile"] as! PFFile

    if let image = self.imageCache.objectForKey(postings.objectId!) as? UIImage {

    cell.imageView.image = image
    println("had this photo in cache")

    } else {

        theImage.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in

        if error != nil {

            println("error caching or downloading image")
            return
        }

        let cellImage = UIImage(data:imageData!, scale: 1.0)
        self.imageCache.setObject(cellImage!, forKey: postings.objectId!)
        cell.imageView.image = cellImage
        println("just added another photo to cache")
        }
    }

    return cell
}


class CollectionViewCell: UICollectionViewCell {

    var objectId: String!

}

回答1:


  1. As @Adrian B said: read about Instruments.
  2. You might consider scaling down the images before you save them, or save an additional smaller copy for display in the table view. It depends how good images you need - presumably for the table view not as large as full scale pictures with MB of data. Actually, the images will also look better if they are properly scaled. This by itself should take care of the delays.
  3. You have your onw cache strategy, but if you want to improve performance, try SDWebImage (see: https://github.com/rs/SDWebImage). This library caches images and downloads them asynchronously.


来源:https://stackoverflow.com/questions/31931592/ios-memory-warnings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!