UIGraphicsGetImageFromCurrentImageContext内存泄漏与预览

我正尝试在PDF中创build预览页面的图像,但是在释放内存时遇到了一些问题。

我写了一个简单的testingalgorithm循环的问题, 应用程序崩溃接近第40次迭代

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"myPdf.pdf"]; CFURLRef url = CFURLCreateWithFileSystemPath( NULL, (CFStringRef)pdfPath, kCFURLPOSIXPathStyle, NO ); CGPDFDocumentRef myPdf = CGPDFDocumentCreateWithURL( url ); CFRelease (url); CGPDFPageRef page = CGPDFDocumentGetPage( myPdf, 1 ); int i=0; while(i < 1000){ UIGraphicsBeginImageContext(CGSizeMake(768,1024)); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0); CGContextFillRect(context,CGRectMake(0, 0, 768, 1024)); CGContextSaveGState(context); CGContextTranslateCTM(context, 0.0, 1024); CGContextScaleCTM(context, 1.0, -1.0); CGContextDrawPDFPage(context, page); CGContextRestoreGState(context); // -------------------------- // The problem is here (without this line the application doesn't crash) UIImageView *backgroundImageView1 = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()]; // -------------------------- UIGraphicsEndImageContext(); [backgroundImageView1 release]; NSLog(@"Loop: %d", i++); } CGPDFDocumentRelease(myPdf); 

上述行似乎会产生内存泄漏,但是, 仪器不会显示内存问题;

我能逃避这种错误吗?有人可以用哪种方式解释我? 有没有其他的方式来显示PDF的预览?

UPDATE

我认为这个问题不是由UIGraphicsGetImageFromCurrentImageContext()方法创build的UIImage的释放,而是使用这个autorelease图像创build的UIImageView释放。

我已经分三步执行代码:

 UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext(); UIImageView *myImageView = [[UIImageView alloc] init]; [myImageView setImage: myImage]; // Memory Leak 

第一和第二行不会产生内存泄漏,所以我认为方法UIGraphicsGetImageFromCurrentImageContext不是问题。

我也尝试如下,但问题依然存在:

 UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage]; 

我认为在UIImageView的版本中有一个内存泄漏,它包含一个具有autorelease属性的UIImage。

我试图写我的对象UIImageViewinheritance一个UIView在这个线程中解释。

这个解决scheme的工作,但不是很优雅,这是一个解决方法,我宁愿使用对象UIImageView解决内存问题。

问题是这样的:

 UIGraphicsGetImageFromCurrentImageContext() 

返回一个自动发布的UIImage 。 autorelease池持有这个图像,直到你的代码返回到runloop的控制,你不这样做很长一段时间。 为了解决这个问题,你将不得不在while循环的每次迭代(或每隔几次迭代)中创build一个新的自动释放池。

我知道这是一个古老的问题,但是我刚刚在头上撞了我的头几个小时。 在我的应用程序不断呼吁

 UIImage *image = UIGraphicsGetImageFromCurrentImageContext() 

在一个循环中,尽pipe我调用了image = nil, 不知道应用程序在释放之前会保留多长时间的内存,但是对于我的应用程序来说,获取内存警告然后崩溃确实足够长。

我设法解决它最终通过包装在@autoreleasepool调用/使用UIGraphicsGetImageFromCurrentImageContext()图像的代码。 所以我有:

 @autoreleasepool { UIImage *image = [self imageWithView:_outputImageView]; //create the image [movie addImage:image frameNum:i fps:kFramesPerSec]; //use the image as a frame in movie image = nil; } 

希望可以帮助别人。

这段代码是否在主线程上运行? UIGraphicsGetImageFromCurrentImageContext( 链接 )的文档说,它必须以这种方式运行。

你可以像下面那样更新它

得到一个UIimage的循环

rendered_image = UIGraphicsGetImageFromCurrentImageContext();