大量内存消耗:ImageIO_jpeg_Data [英] Massive Memory Consumption: ImageIO_jpeg_Data
问题描述
我有一个TableViewController,它显示用户图像和每行条目一些文本.该图像通过"cellForRowAtIndexPath"方法加载:
I've got a TableViewController that shows an user image and some text per row entry. This image is loaded in the "cellForRowAtIndexPath" method:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : ApplicantsCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ApplicantsCell
{...}
let image = UIImage(named: "avatar")
cell.applicantImage.image = image
if let applImage = applicant.image as PFFile? {
applImage.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.applicantImage.image = image
}
}
}
return cell
}
每次我重新打开应用程序并转到此TableViewController时,Instruments都会向我显示,将创建一个新的"ImageIO_jpeg_Data"对象,而旧的对象将永远不会释放.每个对象大约需要13 MB的内存...因此,经过几次迭代,内存使用量超过了100 MB并继续...: 内存使用情况http://twail.net/stack/screen.png .
Every time I re-open the app and go to this TableViewController, Instruments shows me, that a new "ImageIO_jpeg_Data" object is created and the old ones get never released. Each of this objects takes about 13 MBs of memory... So after a few iterations, the memory usage passes 100 MB and goes on...: Memory Usage http://twail.net/stack/screen.png.
在模拟器中触发内存不足警告不会释放任何内存...
And triggering a low memory warning in the simulator does not free any memory...
有人可以帮我如何释放内存吗?
Can somebody help me how I can deallocate memory?
推荐答案
您做错了两件事.
首先,在将图像添加到单元格之前,请始终将图像缩小到实际的显示尺寸.仅在内存中保留13 MB的图像,以便您可以在单元格中显示该图像的缩略图版本是错误的.
First, always scale the image down to the actual display size before adding it to the cell. Keeping a 13 MB image in memory just so you can show a tiny thumbnail version of that image in a cell is just wrong.
第二,此代码毫无意义,会给您带来麻烦:
Second, this code makes no sense and will get you in trouble:
if error == nil {
let image = UIImage(data: imageData!)
cell.applicantImage.image = image
}
请记住,单元格已被重用,因此在运行此代码时,cell
指向的单元格可能不再存在于接口中,或可能显示表的另一行(因为已被重用) .而是将(按比例缩小的)图像存储在数据模型中,然后重新加载表.
Remember, the cells are reused, so by the time this code runs, the cell pointed to by cell
may no longer exist in the interface, or may be showing a different row of the table (because it was reused). Instead, store the (scaled-down) image in the data model and reload the table.
这篇关于大量内存消耗:ImageIO_jpeg_Data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!