【发布时间】: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!
}
【问题讨论】:
-
我建议您阅读 Apple 提供的有关跟踪内存使用情况的文档并修改 Instruments 以了解具体是什么消耗了您的内存。 developer.apple.com/library/ios/documentation/Performance/…