CGLayerRef in NSValue - when to call retain() or release()?

戏子无情 提交于 2019-12-20 05:42:20

问题


I am caching some graphics onto CGLayers and then storing them in NSValue objects using @encode (so as to store them in an array). I just wanted to make sure that I handle the retain/release correctly...

I cache the graphics and store them in the array something like this:

// Create an NSMutableArray "newCache"
CGLayerRef drawingLayer = CGLayerCreateWithContext(context, bounds.size, NULL);
CGContextRef drawingContext = CGLayerGetContext(drawingLayer);

// Do some drawing...

[newCache addObject:[NSValue valueWithBytes:&drawingLayer objCType:@encode(CGLayerRef)]];
CGLayerRelease(drawingLayer);      // Is this release correct?

And then later on I retrieve the layer:

CGLayerRef retrievedLayer;
[(NSValue *)[cacheArray objectAtIndex:index] getValue:&retrievedLayer];

// Use the layer...

// Should I release retrievedLayer here?

Am I right to assume that the layer needs releasing after being added to the array (the last line in the first code snippet)? I assumed this is the case since I called a create function earlier in the code. Is the NSValue then keeping track of the layer data for me? Does the retrievedLayer need manually releasing after being used?

Thanks


回答1:


NSValue doesn't know about Core Foundation types, so it will not retain or release the CGLayer. (The @encoded type string pretty much just tells it how big the value is; it does not tell it anything about memory management.)

You must not release the layer until you are fully done with both the layer and the NSValue.

Or, better yet, just put the CGLayer into the array. All Core Foundation objects are compatible with NSObjects for purposes of memory management (discussed previously), which has the practical effect that you can put CF objects into NSArrays and vice versa. Since CGLayers are CF objects, this means that you can put the CGLayer into the array without boxing it in another object.



来源:https://stackoverflow.com/questions/7220398/cglayerref-in-nsvalue-when-to-call-retain-or-release

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