I am writing code intended to work both under ARC and under Garbage Collection.
Here’s a bit of code that uses Core Foundation as it might be written specifically for ARC:
CFTypeRef ref=CFCopySomething();
// At this point ref has retain count 1.
id obj=(__bridge_transfer id)ref;
// Ref still has retain count 1 but is now managed by ARC.
[obj doSomething];
// ARC will release ref when done.
It seems this is equivalent to:
CFTypeRef ref=CFCopySomething();
// At this point ref has retain count 1.
id obj=(__bridge id)ref;
// Now ref has retain count 2 due to assigning to strong variable under ARC.
CFRelease(ref)
// Now ref has retain count 1.
[obj doSomething];
// ARC will release ref when done.
The benefit of the latter being that the CFRelease call allows the GC to collect the object. But I’m not sure about calling the CFRelease after transferring to ARC with the bridge-casted assignment.
It certainly seems to work. Is this code OK?
Your second code snippet is correct, and indeed is the best way to handle both ARC and GC. You could also use CFMakeCollectable when creating the object, and then have the CFRelease done as follows:
if ([NSGarbageCollector defaultCollector] == NULL) CFRelease(myCFString)
But I like better what you have with just one call that works for both environments.