我正在尝试使用从 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!
}
最佳答案
- 正如 @Adrian B 所说:阅读有关 Instruments 的内容。
- 您可以考虑在保存图像之前缩小图像,或者保存额外的较小副本以在表格 View 中显示。这取决于您需要多好的图像 - 大概是表格 View 不像带有 MB 数据的全尺寸图片那么大。事实上,如果适当缩放图像也会看起来更好。这本身应该可以解决延迟问题。
- 您有自己的 onw 缓存策略,但如果您想提高性能,请尝试 SDWebImage(请参阅: https://github.com/rs/SDWebImage )。该库缓存图像并异步下载它们。
关于iOS 内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31931592/