__bridge_retained 與 __bridge_transfer

感覺網(wǎng)上對__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對象引用計數(shù)+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的引用計數(shù)即obj的引用計數(shù)

打印結果為
the retain count =2
the retain count is 1

__bridge_retained使該對象引用計數(shù)+1, ARC和Core Foundation同時持有該對象(可以這么理解, 而不是cfObject持有obj), 在出了obj作用域的時候ARC使obj引用計數(shù)-1. 但Core Foundation仍持有obj, 所以引用計數(shù)不為0.

  1. __bridge_transfer
    用于Core Foundation對象強轉為Foundation對象, Core Foundation對象引用計數(shù)-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放棄了所有權, 引用計數(shù)-1;

? 綜上:
__bridge_retained給了Core Foundation所有權
__bridge_transfer剝奪了Core Foundation所有權
ARC一直持有所有權, 只是會不會和Core Foundation共享一個對象的問題

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容