objective-c - 双模 ARC/GC 和 Core Foundation 桥接

标签 objective-c garbage-collection automatic-ref-counting core-foundation

我正在编写旨在同时在 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/

相关文章:

iphone - 优化 UIScrollView 中的图像加载

java - young GC 暂停与 STW 暂停

ios - 尽管 block 已被复制,但 block 正在阻止释放

ios - Swift:CGPathRelease 和 ARC

objective-c - NSDatePicker 更改日期方法运行两次!(mac app)

iphone - TableView :willDisplayHeaderView:inSection: not called when running for iOS 6. 1

objective-c - 尝试将文本字段文本设置为字符串时出错

javascript - Chrome 内存/垃圾收集问题

python - 在Python中,如何卸载生成的类

ios - 为什么直接将对象分配给属性时 ARC 无法正常工作