There seems to be a memory leak in this code, but I cannot find it. What am I doing wrong? Specifically, lines 1 and 2 add to the apps memory usage, and only the memory from line one goes away when the context is ended.
UIGraphicsBeginImageContext(imageView.bounds.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
EDIT 1: Full method code below:
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setFrame:CGRectMake(0, 0, self.view.frame.size.width + 16 - ((int)self.view.frame.size.width % 16), self.view.frame.size.height + 16 - ((int)self.view.frame.size.height % 16))]; // If image width and height is not a multiple of 16, the video becomes distorted when written to a file
imageView.contentMode = UIViewContentModeScaleToFill;
[imageView addSubview:[[UIImageView alloc] initWithImage:[ViewController makeRedCircle]]];
UIGraphicsBeginImageContext(imageView.bounds.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
There is nothing inherent about your code that leaks:
UIGraphicsBeginImageContext(imageView.bounds.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Nor is there any evidence of a leak. To test, I created an app whose only code is as follows:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView* imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView* imageView = self.imageView;
for (int i = 0; i <= 10; i++) {
// Here is your code in action!
UIGraphicsBeginImageContext(imageView.bounds.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
@end
There is no leak; successive iterations of the loop do not add to the app's memory.
Therefore we can conclude that if your app's memory is growing, it's because of something else you're doing (such as what you're doing with the image later on).