OGeek|极客世界-中国程序员成长平台

标题: ios - 显示 pdf 图像时 Core Graphics 内存泄漏 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:57
标题: ios - 显示 pdf 图像时 Core Graphics 内存泄漏

我有一个加载 pdf 图像数据的 UIImageView View 的子类,因此我可以在我的 View 中拥有与分辨率无关的图形。对于既定目的效果很好,但是根据仪器泄漏配置文件,我会因此而发生内存泄漏。

下面是我认为应该对泄漏负责的代码。我正在努力追查问题,但我对如何查明问题有点模糊。

- (id)initWithPDFResourceAtPathNSString *)path centerCGPoint)center {
    if ((self = [super init])){
        CGPDFPageRelease(pageRef);
        CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path]);
        pageRef = CGPDFDocumentGetPage(documentRef, 1);
        CGPDFPageRetain(pageRef);
        CGPDFDocumentRelease(documentRef);
        [self setBounds];
    }
    return self;
}

-(void)setBounds {
    [self setBounds:CGRectApplyAffineTransform(CGPDFPageGetBoxRect(pageRef, kCGPDFMediaBox), CGAffineTransformMakeScale(scaleH, scaleV))];
    size = self.bounds.size;
    [self getPDFimage];
}

-(void)getPDFimage {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(context, scaleH, scaleV);
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
    CGContextDrawPDFPage(context, pageRef);
    [self setImage:UIGraphicsGetImageFromCurrentImageContext()];
}



Best Answer-推荐答案


您忘记调用 UIGraphicsEndImageContext()。将您的代码更改为:

UIImage *image = [self setImage:UIGraphicsGetImageFromCurrentImageContext()];
UIGraphicsEndImageContext();
return image;

EDIT1:您的代码有这个 pageRef 变量 - 它是 ivar 还是静态变量?如果是 ivar,最好在 dealloc 方法中使用 CGPDFPageRelease() 释放它。 [确实应该是ivar]

EDIT2:请参阅附加的对象分配屏幕截图。您可以看到类型和当前数量及其从多到少的顺序。

enter image description here

EDIT3:所有其他方法都失败了,创建一个有同样问题的演示项目并将其发布到 Dropbox。

EDIT4:代码上传到:here (我要到 5 月 28 日才能看到它)

EDIT5:问题是 pageRef 从未发布过。所以:

1) 从您的 init 方法中删除它,因为它什么都不做:

CGPDFPageRelease(pageRef);

2 并将其移至新的 dealloc 方法:

- (void)dealloc
{
    CGPDFPageRelease(pageRef);
}

关于ios - 显示 pdf 图像时 Core Graphics 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16565561/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4