// This WILL NOT increment the image's retain count.
CGImageRef iRef = (__bridge CGImageRef)array[0];
// This WILL increment the image's retain count.
CGImageRef iRef = (__bridge_retained CGImageRef)array[0];
Since __bridge_retained
increments the retain count, you need to decrement the retain count at some point later. Because __bridge_retained
acts like CFRetain
, Apple created a __bridge_retained
wrapper called CFBridgingRetain
that reminds you of this:
// This WILL increment the image's retain count.
CGImageRef iRef = CFBridgingRetain(array[0]);
Whenever you see CFRetain
or CFBridgingRetain
, you know you need to release the object at some point later.
Similarly, you can use CFBridgingRelease
instead of __bridge_transfer
to decrement the retain count of a CF object. Example:
[_array addObject:CFBridgingRelease(renderedRef)];
You can use CFBridgingRelease
to balance a CFRetain
or a CFBridgingRetain
. It returns an id
that ARC manages.
A normal NSMutableArray
retains each of its elements. You can tell it to become empty:
[_array removeAllObjects];
When you do this, it will release each of its elements, balancing the retain it performed on each element.
Thus there is no memory leak in this code:
CGImageRef image = CGImageCreate(...);
[_array addObject:CFBridgingRelease(image)];
[_array removeAllObjects];
or in this code:
CGImageRef image = CGImageCreate(...);
[_array addObject:CFBridgingRelease(image)];
CGImageRef image2 = CFBridgingRetain([_array lastObject]);
[_array removeLastObject];
CGContextDrawImage(gc, rect, image2);
CGImageRelease(image2);