我正在尝试创建 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);
上述行似乎会产生内存泄漏,
然而,仪器没有表现出记忆问题;
我可以避免这种错误吗?有人可以用哪种方式解释我?
还有其他方法可以显示 pdf 预览吗?
UPDATE
我认为问题不在于发布UIImage
通过方法创建的UIGraphicsGetImageFromCurrentImageContext()
但释放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 https://stackoverflow.com/questions/4644912/iphone-uiimageview-setimage-leaks.
这个解决方案有效,但不是很优雅,它是一种解决方法,我更喜欢使用对象 UIImageView 解决内存问题。