Dynamic Binding

Managing Toll-free Bridging in an ARC’ed Environment

Sooner or later every Objective-C programmer moving to ARC will be confronted with the unhappy compiler requesting him to perform a so-called “bridged cast” where he once did a “toll-free” cast between Objective-C object pointers and pointers to C types like CoreFoundation types. Unfortunately Apple’s documentation on this topic doesn’t cut it yet.

Fortunately the ever knowledgeable Mike Ash has written an excellent blog post on ARC as a whole and toll-free bridging in particular which I strongly recommend to read. Drawing on this I will rephrase the bottom line on bridged casts in a rather informal but still catchy manner right here.

So, what is ARC concerned about when your program turns an Objective-C object pointer into some C type pointer and vice versa? It’s interest is all about:

Who takes care of releasing that object later on? You the programmer or me, ARC?

Well, you can tell ARC via the following cast modifiers:

__bridge_retained (n.b.: only use it when casting from object pointer to C type pointer): I (the programmer) need to reference this object for some time in the dark world of C type pointers which is opaque to you, ARC. So please, please do not release this object while I still need it. I (the programmer) promise to release it myself (in the dark world) when I’m done with it

__bridge_transfer (n.b.: only use it when casting from C type pointer to object pointer): I (the programmer) hand over to you, ARC, an object that I own and that I am no longer interested in in the dark world of C type pointers that is opaque to you. Whenever you, ARC, are done with that object please release it yourself, because you know the right time and thus save me some work not having to do it myself.

__bridge: ARC, you keep balancing out your retains and releases as I keep balancing out mine in the dark world of C type pointers which is…. Whenever I need to hold on to an object in the dark world I will retain it myself and release it when appropriate. I don’t need any extra contract with you, ARC.

Mike Ash also excercises excellent examples to illustrate these three semantics.