How to Autorelease a CGImageRef?

北城以北 提交于 2019-12-19 04:10:51

问题


I have a method that returns a CGImageRef object. It contains this call:

CGImageRef posterFrame = [avAssetImage copyCGImageAtTime:time actualTime:nil error:&error];
...
return posterFrame;

This situation, as I understand it, calls for an autorelease. But I have no idea how to do it. I've tried using CFCollectable(), but it doesn't work. Any ideas?


回答1:


If you're using garbage collection, use CFMakeCollectable(posterFrame). If you're using traditional memory management, it's very straightforward:

return (CGImageRef)[(id)posterFrame autorelease];

You cast the CFTypeRef (in this case, a CGImageRef) to an Objective-C object pointer, send it the -autorelease message, and then cast the result back to CGImageRef. This pattern works for (almost) any type that's compatible with CFRetain() and CFRelease().




回答2:


Core Graphics (and Core Foundation) doesn't have an autorelease pool, so if you want to return your CGImageRef you need to either name your function containing Create(f.e. MyCreatePosterImage()) or return UIImage object instead:

CGImageRef posterFrame = [avAssetImage copyCGImageAtTime:time actualTime:nil error:&error];
UIImage *result = [UIImage imageWithCGImage:posterFrame];
CGImageRelease(posterFrame);
return result;


来源:https://stackoverflow.com/questions/7061149/how-to-autorelease-a-cgimageref

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