Memory Leak iOS (UIImageView,UIImage,CGImage) not

2019-07-05 06:26发布

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条回答
不美不萌又怎样
2楼-- · 2019-07-05 07:17

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];
    }
查看更多
登录 后发表回答