To bridge or not to bridge, that is my question


#1

I was doing a bit of experimenting with the following lines of code on page 403:

UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
CGImageRef image = layerImage.CGImage;
[boxLayer setContents:(__bridge id)image];

When I removed the __bridge part from the last line, the compiler issues an error about casting CGImageRef to an Objective C pointer requires a bridged cast. Ok no problem, I agree with that error. But then to my surprise, the compiler would not complain if I rewrote the code to the following (and the app still works):

UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
[boxLayer setContents:(id)layerImage.CGImage];

Can anyone explain why the compiler remained quiet with the rewritten code and more importantly is it “correct” (in regards to memory management) to write it this way without the __bridge keyword?

Thanx in advance!


#2

I actually believe the book explained this in an earlier chapter noting the __bridge ensures that everything is compatible and there are no unexpected issues. It’s more of a precaution than anything.


#3

I think it has something to do with the fact that you are assigning layerImage.CGImage to image. Doing this means that the pointer earns an owner. The __bridge is needed to keep the reference counts straight.

On the other hand, when you skip the intermediate assignment, the reference count (in going from CG…Ref to ARC) comes out “right”.

Only an “uneducated” guess on my part. :slight_smile: