1)CGImageRef的释放
You don't own theCGImageRefrawImageRefbecause you obtain it using[image CGImage]. So you don't need to release it.
However, you ownrawPixelDatabecause you obtained it usingCGDataProviderCopyDataand must release it.
CGDataProviderCopyData
Return Value: A new data object containing a copy of the provider’s data. You are responsible for releasing this object.
2)UIGraphicsGetImageFromCurrentImageContext
查了N多资料,寻找到了另一种替代方法,效果要好一些,但也没办法彻底解决这个问题
CGImageRef cgImage2 = CGBitmapContextCreateImage(ctx);
UIImage *fixed = [UIImage imageWithCGImage:cgImage2];
CGImageRelease(cgImage2);
3)最终解决办法:
因为是修改别人的代码,优化时无意中解决了此问题,原来的调用方法是在A函数中调用UIGraphicsGetImageFromCurrentImageContext(在C函数中)生成UIImage,然后传递给B函数去处理,这样内存会暴涨。现在将C函数调用生成UIImage放到B函数中生成并使用,这样就能得到及时释放。
4)额外的建议
因出问题应用模块是开启摄像头在不停检测每一帧图像并检测人脸,这样每秒会处理30次,导致临时的UIImage对象迅速增多,占用内存过大。在收到didReceiveMemoryWarning通知时,调用AVCaptureSession类的停止运行,然后再重新运行。
[self.captureSessionstopRunning];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1)),dispatch_get_main_queue(), ^{
[self.captureSessionstartRunning];
});