【发布时间】:2012-03-17 02:54:36
【问题描述】:
我正在编写旨在在 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。
这似乎确实有效。这段代码可以吗?
【问题讨论】:
-
值得一提的是,
__bridge强制转换对非 ARC 编译单元没有任何意义,即编译器在使用--objc-gc编译时会简单地忽略它们,从而使您的第二个代码 sn- p 与 ARC 和 GC 兼容。 (只是说因为我不得不搜索。)
标签: objective-c garbage-collection automatic-ref-counting core-foundation