Reputation: 3740
My app loops through array of image paths and merges all those images into one. The code is below. However, the app crashes when I release the image with (gdb) printed out in my console. If I remove image release line, then it works fine but this may probably lead to memory leaks. Please look at this code and explain why this happens and what can be improved. Thank you.
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width*len+padding*len+padding,
height+padding*2),
YES, 0.0);
do{
//draw image
path = (NSString*)[_imageData objectAtIndex:i];
UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
[img release]; //APP CRASHES HERE BUT WORKS IF THIS LINE REMOVED
i++;
}while (i<len);
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(result, self,
@selector(image:didFinishSavingWithError:contextInfo:),
nil);
Upvotes: 0
Views: 218
Reputation: 318804
The problem is that you are not releasing the allocated image. You are releasing the autoreleased cropped image and leaking the allocated image.
Change this:
UIImage * img = [[[UIImage alloc] initWithContentsOfFile:path]
cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[img drawAtPoint: CGPointMake(width*i+padding*i+padding,padding) blendMode:kCGBlendModeNormal alpha:1];
[img release];
to:
UIImage *original = [[UIImage alloc] initWithContentsOfFile:path];
UIImage *cropped = [original cropCenterAndScaleImageToSize:CGSizeMake(width, height)];
[cropped drawAtPoint:CGPointMake(width * i + padding * i + padding, padding) blendMode:kCGBlendModeNormal alpha:1];
[original release];
I'm assuming the cropCenterAndScaleImageToSize:
is some category method that returns an autoreleased UIImage
reference.
Upvotes: 3