2014-09-13 440 views
2

以下代碼段使用UIImageCIImage保存到磁盤。無法將CIImage保存到iOS上沒有內存泄漏的文件

- (void)applicationWillResignActive:(UIApplication *)application 
{ 
    NSString* filename = @"Test.png"; 

    UIImage *image = [UIImage imageNamed:filename]; 

    // make some image processing then store the output 
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage]; 

#if 1// save using context 

    CIContext *context = [CIContext contextWithOptions:nil]; 
    CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent]; 
    image = [UIImage imageWithCGImage:cgiimage]; 

    CGImageRelease(cgiimage); 

#else 

    image = [UIImage imageWithCIImage:processedImage]; 

#endif 

    // save the image 

    NSString *filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[@"../Documents/" stringByAppendingString:filename]]; 

    [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]; 
} 

然而,漏CGImageRef即使它是通過調用CGImageRelease

enter image description here

放開。如果有#if 1行更改爲#if 0,該UIImage直接從CIImage有創建沒有內存泄漏,但是UIImage未保存到磁盤

回答

4

裹自動釋放池裏面的節約:

- (void)applicationWillResignActive:(UIApplication *)application 
{ 
    NSString* filename = @"Test.png"; 

    UIImage *image = [UIImage imageNamed:filename]; 

    // make some image processing then store the output 
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage]; 

    @autoreleasepool { 
     CIContext *context = [CIContext contextWithOptions:nil]; 
     CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent]; 
     image = [UIImage imageWithCGImage:cgiimage]; 

     CGImageRelease(cgiimage); 

     // save the image 
     NSURL *documentsDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject]; 
     NSURL *fileURL = [documentsDir URLByAppendingPathComponent:filename]; 

     [UIImagePNGRepresentation(image) writeToURL:fileURL atomically:YES]; 
    } 
} 

另外請注意,我如何更新你檢索文件目錄爲iOS 8的工作(more info)。

+0

即使使用@autoreleasepool也不能解決問題:http://stackoverflow.com/questions/32685756/memory-leak-in-cmsamplebuffergetimagebuffer – loretoparisi 2015-09-27 17:40:06