释放 CGImage (CGImageRef)
我很好奇我是否使用 CGImageRef 遵循正确的内存管理,我正在通过几种方法传递它(因为它是 CG 对象,我假设它不支持自动释放)。 非 NSObject 的内存管理以及与其他 NSObject 的交互对我来说仍然有些新鲜。
我正在做的事情是:
我使用 CGBitmapContextCreateImage (保留计数 1)在图像缓存管理器中创建 CGImageRef,并将其添加到 NSMutableDictionary (保留计数 2)。
当 CALayers 使用图像时,我分配了layer.contents(保留计数+1),并在删除图层之前使用layer.contents = nil(保留计数-1)清除内容。
最后,当清除纹理时,我调用 CGImageRefRelease 和 [NSMutableDictionary removeObject] 将保留计数设置为 0。
这是正确的方法吗?
I'm curious if I'm following proper memory management with CGImageRef, which I'm passing through several methods (since it's CG object, I assume it doesn't support autorelease). Memory management with non-NSObjects and interaction with other NSObjects is still somewhat new to me.
Here what I'm doing:
I'm creating the CGImageRef inside my image cache manager with CGBitmapContextCreateImage (retain count 1), and adding it to the NSMutableDictionary (retain count 2).
When CALayers use the image, I assign with layer.contents (retain count +1), and clearing contents with layer.contents = nil (retain count -1) before removing the layer.
Finally, when clearing the texture, I call CGImageRefRelease and [NSMutableDictionary removeObject] to have retain count as 0.
Is this a proper way to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Core Foundation 对象(所有 Core Graphics 对象都是)支持自动释放。
您描述的步骤应该可以正常工作,并且不会泄漏或过度释放对象。
我使用 CFRelease 而不是像 CGImageRelease 这样的特定类发布函数,但这纯粹是出于风格问题。 我只需要注意
NULL
:CGImageRelease
检查NULL
,而CFRelease
在传递时会崩溃空。 使用 CGImageRelease 及其同级意味着您不必担心这一点。
我假设您的意思是
removeObject:forKey:
,而不是removeObject
(它不存在,而且无论如何也没有地方可以指定对象)。Core Foundation objects (which all Core Graphics objects are) do support autorelease.
The steps you describe should work just fine and not leak or over-release the object.
I use
CFRelease
instead of specific-class release functions likeCGImageRelease
, but purely as a matter of style. I just have to beware ofNULL
:CGImageRelease
checks forNULL
, whereasCFRelease
will crash when passedNULL
. UsingCGImageRelease
and its siblings means you don't have to worry about this.I'm assuming you meant
removeObject:forKey:
, notremoveObject
(which doesn't exist and wouldn't have somewhere to specify an object anyway).