感觉网上对__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对象强转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.
- __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共享一个对象的问题