0

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

4

1 回答 1

1

NSValue 不知道 Core Foundation 类型,因此它不会保留或释放 CGLayer。(@encoded 类型的字符串几乎只是告诉它值有多大;它没有告诉它任何关于内存管理的信息。)

在完全完成图层和 NSValue 之前,不得释放图层。

或者,更好的是,只需将 CGLayer 放入数组中。出于内存管理的目的(之前讨论过),所有 Core Foundation 对象都与 NSObjects 兼容,这具有您可以将 CF 对象放入 NSArrays 的实际效果,反之亦然。由于 CGLayer 是 CF 对象,这意味着您可以将 CGLayer 放入数组中,而无需将其装箱到另一个对象中。

于 2011-08-28T16:23:20.760 回答