Skip to content

Instantly share code, notes, and snippets.

@DuncanMC
Last active August 29, 2015 13:57
Show Gist options
  • Save DuncanMC/9677908 to your computer and use it in GitHub Desktop.
Save DuncanMC/9677908 to your computer and use it in GitHub Desktop.
An explanation of iOS/Mac OS bridging casts
Using Core Foundation (CF) objects in ARC
ARC makes most aspects of memory management easier, but managing CF objects is still up to you, and converting
between NSObjects and CFObjects is actually more complicated.
If you create a CF object that follows the "Create Rule" (you own an object that is created with a method with
"create" or "copy" its name) you have to release it.
In ARC, that's still true.
Where it gets confusing is when you need to cast objects between CF objects and NSObjects.
There are 3 "bridging cast" operators that let you deal with converting between CF types and NSObject types.
__bridge simply converts between CF and Objective C objects. It works in both directions. It does not adjust
retain counts for you.
__bridge_transfer (or the macro CFBridgingRelease() ) converts a CF object to an NSObject. It is used for
"toll-free bridged" CF objects. It lets you pass a CF object that you own to it's Objective C equivalent.
The CF object is released in the process, and ARC takes ownership of the equivalent NSObject.
__bridge_retain (or the macro CFBridgingRetain() ) does the reverse of __bridge_transfer. It lets you convert
an autoreleased NSObject to it's CF equivalent. The bridge CFRetains the resulting CF object, so you have to
CFRelease it when you're done with it.
For example, say you ask the address book for a string using , ABRecordCopyValue . In that case, you are
converting a CFString, which is toll-free bridged to NSString, to it's NSString equivalent. The
ABRecordCopyValue method has copy in it's name, so it follows the "Create rule" for CF objects. You own it
and need to release it. Thus, you
should use this line:
NSString *fname = (NSString*) CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
After that line, fname holds a "strong" reference to the converted CFString, and will release it when it
goes out of scope. Thus you can forget about the CF object and treat it as an NSObject from then on.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment