Releasing renderInContext result within a loop

懵懂的女人 提交于 2019-11-29 04:16:13

Naturally after 3 days of experimenting, I find the answer (an answer, anyway, and I would be glad of comments on this) within the hour.

I add

background.layer.contents = nil;

after

UIGraphicsEndImageContext();

and the cached memory in the layer is uncached :).

I am not using a UIImageView, so setting layer.contents = nil did not work for me. However, I found a different solution that, while not ideal, does work. It appears that the memory allocated by renderInContext does not get freed until the main_queue is idle. So, I did the following:

dispatch_queue_t queue = dispatch_queue_create("com.example.imageprocessing", DISPATCH_QUEUE_SERIAL);

for (int k = 0; k < images.count; ++k) {
    dispatch_async(queue, ^{
        dispatch_sync(dispatch_get_main_queue(), ^{
            @autoreleasepool {
                ...
                UIGraphicsBeginImageContext(self.view.bounds.size);
                [view.layer renderInContext:UIGraphicsGetCurrentContext()];
                image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                ...
            }
        }
    }
}

This solved my memory issue. I'm not processing a lot of images, so I don't know how the performance is affected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!