Memory Leak iOS (UIImageView,UIImage,CGImage) not

2019-07-05 07:09发布

问题:

Im trying to implement a simple video stream but for some reason my memory won't get freed:

(void)updateImage:(UIImage *)image{
  self.indicator.hidden = TRUE;
  //CGImageRelease([self.imageView.image CGImage]);
  self.imageView.image = nil;
  self.imageView.image = image;
  [self.imageView setNeedsDisplay];
}

If I use

CGImageRelease([self.imageView.image CGImage]);

memory will be freed. But when I return to a previous view controller the app will crash as it tries to free the allocated memory for that image, which I already freed. This method is called from a async task which creates an image using:

UIImage *image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
CGDataProviderRelease(provider);
CFRelease(data);

As I understood it the UIImage now owns the CGImage and I shouldn't have to release it. So is there anyway to ensure that the UIImage is freed when I updated the UIImageView with a new image?

回答1:

Ok so I finally figured out the problem.

As I said I was using some background thread to perform the image update, the solution was to add it as a autorelease pool as following:

   @autoreleasepool {
        [self.delegate performSelectorOnMainThread:@selector(updateImage:) withObject:[self fetchImage] waitUntilDone:NO];
    }