iOS 内存警告

标签 ios swift memory

我正在尝试使用从 Parse 数据库下载的图像填充 Collection View ,但我收到内存警告,然后偶尔崩溃。有谁知道其他应用程序如何设法呈现这么多图像而不崩溃?有人可以告诉我如何优化我已有的东西吗?这是所有相关代码: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 所说:阅读有关 Instruments 的内容。
  2. 您可以考虑在保存图像之前缩小图像,或者保存额外的较小副本以在表格 View 中显示。这取决于您需要多好的图像 - 大概是表格 View 不像带有 MB 数据的全尺寸图片那么大。事实上,如果适当缩放图像也会看起来更好。这本身应该可以解决延迟问题。
  3. 您有自己的 onw 缓存策略,但如果您想提高性能,请尝试 SDWebImage(请参阅: https://github.com/rs/SDWebImage )。该库缓存图像并异步下载它们。

关于iOS 内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31931592/

相关文章:

iphone - 在 iPhone 中使用 OpenGL ES 画直线?

ios - 具有许多图像的 UITableView 内存使用率高

python - 将大文件逐行读入 Python2.7 时的内存使用

ios - 为什么我的 UIButton 图像大小在模拟器和设备中不同?

iphone - 如何在 iOS 上使用 AVMutableComposition 和 CALayers 将多个 CALayer 添加到视频文件

ios - swift 。设置文本字段中输入的格式

html - Swift/Xcode - 是否可以控制网页上的 HTML 元素?

ios - 上传图片: reduce resolution without loosing quality (Swift)

ios - Objective C 到 Swift - DoWithBlock

java - Eclipse MAT 中的正则表达式类型