感覺網(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.
- __bridge_retained
用于Foundation對象強(qiáng)轉(zhuǎn)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ù)
打印結(jié)果為
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.
- __bridge_transfer
用于Core Foundation對象強(qiáng)轉(zhuǎn)為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);
}
如上代碼, 不調(diào)用CFRelease并沒有任何問題, 使用__bridge_transfer, 及Core Foundation放棄了所有權(quán), 引用計數(shù)-1;
? 綜上:
__bridge_retained給了Core Foundation所有權(quán)
__bridge_transfer剝奪了Core Foundation所有權(quán)
ARC一直持有所有權(quán), 只是會不會和Core Foundation共享一個對象的問題