2016-01-22 217 views
1

这段代码似乎存在内存泄漏,但我找不到它。我究竟做错了什么?具体而言,第1行和第2行增加了应用程序的内存使用情况,并且只有第一行的内存在上下文结束时消失。UIGraphics内存泄漏

UIGraphicsBeginImageContext(imageView.bounds.size); 
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

编辑1: 完整方法如下代码:

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(); 
+1

是什么让你觉得有泄漏? – matt

+0

@matt它每次运行时都会永久性地向内存中添加几兆字节。我使用Xcode在iPhone 6上测试了应用程序。 – mntruell

+1

你使用过仪器吗? - 什么是'图像'?你以后在做什么?换句话说,你可以给我代码,我可以实际运行,以重现你的泄漏? – matt

回答

2

没有什么内在的有关代码泄漏:

UIGraphicsBeginImageContext(imageView.bounds.size); 
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

也不存在泄漏的任何证据。为了测试,我创建了一个应用程序,其唯一代码如下:

@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 

没有泄漏;循环的连续迭代不会添加到应用程序的内存中。因此,我们可以得出结论,如果你的应用程序的内存不断增加,那是因为你正在做的其他事情(比如你以后对图像做了什么)。