Dual ARC / GC and Core Foundation

I am writing code designed to work both in ARC and in the Garbage Collection section.

Here is some code that uses the Core Foundation, as it can 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. 

This seems to be 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 advantage of the latter is that a call to CFRelease allows the GC to assemble the object. But I'm not sure about calling CFRelease after the transfer to the ARC with the destination with the bridge.

This will certainly work. Is this code ok?

+6
source share
2 answers

The second code snippet is correct and really is the best way to handle both ARC and GC. You can also use CFMakeCollectable when creating an object, and then execute CFRelease as follows:

if ([NSGarbageCollector defaultCollector] == NULL) CFRelease (myCFString)

But I like what you have with one call that works for both environments.

+2
source

Nick

Since CFObjects are not processed by ARC, you might want to save manually managed code here. ARC really focuses on Cocoa, not Core Foundation. However, you said that the code works, but it flows? Remember that ARC code with incorrect compiler flags does not work. In this documentation, Apple claims that ARC does not manage CF objects: https://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html . Therefore, I think your __bridge code is leaking and waiting for your confirmation or rejection of a tool leak tool.

Andrew

+1
source

Source: https://habr.com/ru/post/909461/


All Articles