to __bridge or not to __bridge?
to __bridge or not to __bridge?
- Subject: to __bridge or not to __bridge?
- From: Jean-Denis MUYS <email@hidden>
- Date: Mon, 13 Feb 2012 14:20:55 +0000
- Thread-topic: to __bridge or not to __bridge?
I am a bit puzzled by the LLVM 3.0 behavior (Xcode 4E71d if that matters) regarding casting between id and a Core Foundation type.
Here is a sample method that illustrates the issue:
- (void) arcTest:(UIImage *)image
{
CALayer *myLayer = self.view.layer;
myLayer.contents = (id) image.CGImage; // case 1: the compiler is happy
CGImageRef itsCGImage = image.CGImage;
myLayer.contents = (id) itsCGImage; // case 2: the compiler complains
}
This is iOS code, but that shouldn't matter. Here are the facts:
- The CALayer class defines contents thus:
@property (retain) id contents;
And its documentation tells us we typically put a CGImageRef in there.
- The UIImage class defines CGImage thus
@property (nonatomic,readonly) CGImageRef CGImage;
So I understand the need to typecast the CGImageRef to id: the destination is declared as id, the value is CGImageRef.
But what I don't understand, is why the compiler likes case 1 above, but not case 2. On case 2, it complains:
"Cast of C pointer type 'CGImageRef' (aka 'struct CGImage *') to Objective-C pointer type 'id' requires a bridged cast"
Then Xcode suggests two different fixes:
myLayer.contents = (__bridge id) itsCGImage;
myLayer.contents = (__bridge_transfer id) itsCGImage;
I kind-of understand why the compiler needs this qualified cast. But then why doesn't it need it for case 1?
Secondarily, just to check my understanding, the correct qualification is __bridge here, because the destination will balance all retains with releases. Correct? By doing so, the emitted code will leave image.CGImage. On the other hand, with a __bridge_transfer, the compiler will emit a call to release on itsCGImage after the myLayer.contents setter returns. Still correct?
Thanks,
Jean-Denis
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden