我正在编写旨在同时在 ARC 和垃圾收集下工作的代码。
这里有一些使用 Core Foundation 的代码,因为它可能是专门为 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.
这似乎等同于:
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.
后者的好处是 CFRelease 调用允许 GC 收集对象。但是我不确定在使用桥接分配转移到 ARC 后调用 CFRelease。
这似乎确实有效。这段代码可以吗?
最佳答案
您的第二个代码片段是正确的,确实是处理 ARC 和 GC 的最佳方式。您还可以在创建对象时使用 CFMakeCollectable,然后按如下方式完成 CFRelease:
if ([NSGarbageCollector defaultCollector] == NULL) CFRelease(myCFString)
但我更喜欢您只需一次调用即可同时适用于两种环境的功能。
关于objective-c - 双模 ARC/GC 和 Core Foundation 桥接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9468327/