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多資料,尋找到了另一種替代方法,效果要好一些,但也沒辦法徹底解決這個(gè)問題
CGImageRef cgImage2 = CGBitmapContextCreateImage(ctx);
UIImage *fixed = [UIImage imageWithCGImage:cgImage2];
CGImageRelease(cgImage2);
3)最終解決辦法:
因?yàn)槭切薷膭e人的代碼,優(yōu)化時(shí)無意中解決了此問題,原來的調(diào)用方法是在A函數(shù)中調(diào)用UIGraphicsGetImageFromCurrentImageContext(在C函數(shù)中)生成UIImage,然后傳遞給B函數(shù)去處理,這樣內(nèi)存會(huì)暴漲。現(xiàn)在將C函數(shù)調(diào)用生成UIImage放到B函數(shù)中生成并使用,這樣就能得到及時(shí)釋放。
4)額外的建議
因出問題應(yīng)用模塊是開啟攝像頭在不停檢測每一幀圖像并檢測人臉,這樣每秒會(huì)處理30次,導(dǎo)致臨時(shí)的UIImage對象迅速增多,占用內(nèi)存過大。在收到didReceiveMemoryWarning通知時(shí),調(diào)用AVCaptureSession類的停止運(yùn)行,然后再重新運(yùn)行。
[self.captureSessionstopRunning];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1)),dispatch_get_main_queue(), ^{
[self.captureSessionstartRunning];
});