__bridge_retained 与 __bridge_transfer

感觉网上对__bridge_retained 和 __bridge_transfer 的讲解不是很容易理解, 也可能是我的理解能力有问题.
这里讲一下我的理解, 先上一段官方的描述:

__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.

__bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you.
You are responsible for calling CFRelease or a related function to relinquish ownership of the object.

__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.
ARC is responsible for relinquishing ownership of the object.

链接: https://developer.apple.com/library/content/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html

  1. __bridge_retained
    用于Foundation对象强转Core Foundation为对象, OC对象引用计数+1.
    @autoreleasepool {
        CFMutableArrayRef cfObject=nil;
        {
            id obj=[[NSMutableArray alloc] init];
            cfObject=(__bridge_retained CFMutableArrayRef)obj;
            printf("the retain count =%ld\n",CFGetRetainCount(cfObject));
        }
        printf("the retain count is %ld\n",CFGetRetainCount(cfObject));
        CFRelease(cfObject);
    }

注: cfObject即obj, 所以cfObject的引用计数即obj的引用计数

打印结果为
the retain count =2
the retain count is 1

__bridge_retained使该对象引用计数+1, ARC和Core Foundation同时持有该对象(可以这么理解, 而不是cfObject持有obj), 在出了obj作用域的时候ARC使obj引用计数-1. 但Core Foundation仍持有obj, 所以引用计数不为0.

  1. __bridge_transfer
    用于Core Foundation对象强转为Foundation对象, Core Foundation对象引用计数-1.
@autoreleasepool {
        CFMutableArrayRef cfObject=nil;
        {
            id obj=[[NSMutableArray alloc] init];
            cfObject=(__bridge_retained CFMutableArrayRef)obj;
            printf("the retain count =%ld\n",CFGetRetainCount(cfObject));
        }
        printf("the retain count is %ld\n",CFGetRetainCount(cfObject));
        
        id obj = (__bridge_transfer id)cfObject;
        // CFRelease(cfObject);
    }

如上代码, 不调用CFRelease并没有任何问题, 使用__bridge_transfer, 及Core Foundation放弃了所有权, 引用计数-1;

 综上:
__bridge_retained给了Core Foundation所有权
__bridge_transfer剥夺了Core Foundation所有权
ARC一直持有所有权, 只是会不会和Core Foundation共享一个对象的问题

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容