Retain ownership of UIImage created using UIGraphicsGetImageFromCurrentImageContext

I use this code to get screenshots of the window at different times and put the created UIImage into an array that is passed to another UIViewController so that they can be displayed again in the grid. I am trying to release UIImage and the memory usage is never omitted ... how can I use the image here once and keep ownership so that I can free the memory after displaying it.

UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[imagesArray addObject:image];
[image release];

+4
source share
3 answers

UIGraphicsGetImageFromCurrentImageContext() returns "an auto-implementing object containing the contents of the current raster graphics context."

When you add an image to imagesArray, NSMutableArray stores on it and that’s all you need. The memory will be freed when the image is removed from the array.

You should not call release on the image.

+9
source

I had a memory failure in UIGraphicsGetImageFromCurrentImageContext () ... if you create and release a lot of them, you have to wrap them in a new AutoReleasePool for each iteration. Even letting NSRunLoop tick, IT IS NOT SUFFICIENT for Apple / iOS to do housekeeping on the trash lying around it.

eg.

 for( ... ) { @autoreleasepool { UIImage* blah = UIGraphicsGetImageFromCurrentImageContext(); } } 
+2
source

I am having a strange UIImage memory leak using a saved UIImage image from UIGraphicsGetImageFromCurrentImageContext () in the background thread. The problem turned out to be that you should call this function only from the main thread of your application. Caution.

0
source

Source: https://habr.com/ru/post/1332390/


All Articles