iOS内存警告

我试图用一个Parse数据库下载的图像来填充一个集合视图,但是我收到内存警告,偶尔会发生崩溃。 有谁知道其他应用程序如何设法呈现这么多的图像,而不会崩溃? 有人可以告诉我如何优化我已经有的? 以下是所有相关的代码: 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. 正如@Adrian B所说:读了关于仪器。
  2. 您可以考虑在保存图像之前缩放图像,或者保存一个更小的副本以便在表格视图中显示。 这取决于你需要多么好的图像 – 大概对于表格视图来说,不像具有MB数据的全尺寸图片那么大。 实际上,如果图像适当缩放,图像也会更好看。 这本身应该照顾延误。
  3. 你有你的caching策略,但是如果你想提高性能,请尝试SDWebImage(请参阅: https : //github.com/rs/SDWebImage )。 该库caching图像并asynchronous下载。