Nic*_*ore 6 garbage-collection objective-c core-foundation automatic-ref-counting
我正在编写旨在在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.
Run Code Online (Sandbox Code Playgroud)
这似乎相当于:
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.
Run Code Online (Sandbox Code Playgroud)
后者的好处是CFRelease调用允许GC收集对象.但是我不确定在使用桥接分配转移到ARC后调用CFRelease.
它似乎确实有效.这段代码好吗?
您的第二个代码片段是正确的,并且确实是处理 ARC 和 GC 的最佳方法。您还可以在创建对象时使用 CFMakeCollectable,然后按如下方式完成 CFRelease:
if ([NSGarbageCollector defaultCollector] == NULL) CFRelease(myCFString)
但我更喜欢只需一次调用就可以同时适用于两种环境的功能。
| 归档时间: |
|
| 查看次数: |
1119 次 |
| 最近记录: |