草庐IT

ios - UIGraphicsGetImageFromCurrentImageContext 内存泄漏与预览

coder 2023-06-04 原文

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

我写了一个简单的测试算法来循环这个问题, 应用在第 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);

上述行似乎产生了内存泄漏, 但是,instruments 没有显示内存问题;

我可以摆脱这种错误吗?有人可以用哪种方式解释我吗? 还有其他方法可以显示 pdf 的预览吗?

更新

我认为问题不在于 UIGraphicsGetImageFromCurrentImageContext() 方法创建的 UIImage 的发布,而是使用此方法创建的 UIImageView 的发布自动释放图像。

我把这行代码分成了三个步骤:

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

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

我也尝试了以下方法,但问题仍然存在:

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

我认为发布包含具有 autorelease 属性的 UIImage 的 UIImageView 存在内存泄漏。

我尝试编写继承 UIView 的对象 UIImageView,如本文 thread 中所述。 .

此解决方案有效但不是很优雅,这是一种解决方法,我更喜欢使用对象 UIImageView 解决内存问题。

最佳答案

问题是这样的:

UIGraphicsGetImageFromCurrentImageContext()

返回一个自动发布的 UIImage。自动释放池会保留此镜像,直到您的代码将控制权返回给运行循环,而您很长一段时间都不会这样做。要解决这个问题,您必须在 while 循环的每次迭代(或每几次迭代)上创建并排出一个新的自动释放池。

关于ios - UIGraphicsGetImageFromCurrentImageContext 内存泄漏与预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5121120/

有关ios - UIGraphicsGetImageFromCurrentImageContext 内存泄漏与预览的更多相关文章

随机推荐