UIGraphics内存泄漏

时间:2016-01-22 02:09:36

标签: ios objective-c cocoa-touch uigraphicscontext

此代码中似乎存在内存泄漏,但我无法找到它。我究竟做错了什么?具体来说,第1行和第2行会增加应用程序的内存使用量,当上下文结束时,只有第一行的内存消失。

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 个答案:

答案 0 :(得分: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

没有泄漏;循环的连续迭代不会添加到应用程序的内存中。

因此,我们可以得出结论,如果你的应用程序的内存在增长,那是因为你正在做的其他事情(例如你以后对图像所做的事情)。