2016-01-22 218 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 

沒有泄漏;循環的連續迭代不會添加到應用程序的內存中。因此,我們可以得出結論,如果你的應用程序的內存不斷增加,那是因爲你正在做的其他事情(比如你以後對圖像做了什麼)。