【问题标题】:iOS Memory WarningsiOS 内存警告
【发布时间】:2015-08-11 01:07:13
【问题描述】:

我正在尝试使用从 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!

}

【问题讨论】:

标签: ios swift memory


【解决方案1】:
  1. 正如@Adrian B 所说:阅读有关 Instruments 的信息。
  2. 您可以考虑在保存图像之前缩小图像,或者保存一个额外的较小副本以在表格视图中显示。这取决于您需要多好的图像 - 大概是表格视图不如具有 MB 数据的全尺寸图片那么大。实际上,如果适当缩放图像,它们也会看起来更好。这本身应该可以解决延迟问题。
  3. 你有你的onw缓存策略,但如果你想提高性能,试试SDWebImage(见:https://github.com/rs/SDWebImage)。该库缓存图片并异步下载。

【讨论】:

  • 谢谢,我会研究缩小图像和 SDWebImage。我实际上已经使用过泄漏仪器,但没有发现任何泄漏或任何特殊情况
  • 这很酷,除了 SDWebImage 没有实现任何关于内存缓存的“缓存策略”,除了删除内存警告中的所有缓存对象,这不是内存缓存应该有多好操作。
猜你喜欢
  • 2014-12-24
  • 1970-01-01
  • 2012-06-20
  • 2013-10-04
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多