Vazamento de memória UIGraphicsGetImageFromCurrentImageContext com visualizações
Estou tentando criar imagens de pré-visualizações de páginas em um PDF, mas tenho alguns problemas com o lançamento da memória.
Eu escrevi um algoritmo de teste simples que repete o problema,o aplicativo falha perto da 40ª iteração:
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);
A linha acima mencionada parece gerar um vazamento de memória, no entanto,instrumentos não mostra problemas de memória;
Posso escapar desse tipo de erro? Alguém pode me explicar de que maneira? Existem outras maneiras de mostrar visualizações de um pdf?
ATUALIZAR
Eu acho que o problema não é o lançamento deUIImage
criado pelo métodoUIGraphicsGetImageFromCurrentImageContext()
mas o lançamento deUIImageView
criado com esta imagem de autorelease.
Dividi a linha de código em três etapas:
UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
UIImageView *myImageView = [[UIImageView alloc] init];
[myImageView setImage: myImage]; // Memory Leak
A primeira e a segunda linhas não criam vazamentos de memória, então acho que o método UIGraphicsGetImageFromCurrentImageContext não é o problema.
Eu também tentei da seguinte maneira, mas o problema persiste:
UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage];
Eu acho que há um vazamento de memória no lançamento de um UIImageView que contém um UIImage com a propriedade autorelease.
Tentei escrever meu objeto UIImageView herdando uma UIView conforme explicado nestefio.
Esta solução funciona, mas não é muito elegante, é uma solução alternativa, eu preferiria usar o objeto UIImageView para resolver o problema de memória.