【发布时间】:2011-07-04 12:22:00
【问题描述】:
我正在尝试在 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 存在内存泄漏。
如thread 中所述,我尝试编写继承 UIView 的对象 UIImageView。
此解决方案有效但不是很优雅,这是一种解决方法,我更喜欢使用对象 UIImageView 解决内存问题。
【问题讨论】:
-
您使用什么工具来检查内存使用情况?我会查看“分配”和“活动监视器”,它们都可以显示泄漏工具遗漏的内存使用情况。另外,这段代码到底应该做什么?您想创建 1000 个图像视图,然后在不使用它们的情况下摆脱它们?
-
你找到答案了吗?我有同样的问题:S
标签: ios objective-c memory uikit cgcontext