转换函数
CFTypeRef CFBridgingRetain(id x) {
return (__bridge_retained CFTypeRef)x;
}
id CFBridgingRelease(CFTypeRef x) {
return (__bridge_transfer id)x;
}
例:
CFMutableArrayRef cfObject = NULL;
{
id obj = [[NSMutableArray alloc] init];
cfObject = CFBridgingRetain(obj);
CFShow(cfObject);
printf("retain count = %d\n", CFGetRetainCount(cfObject));
}
printf("retain count after the scope = %d\n", CFGetRetainCount(cfObject));
CFRelease(cfObject);输出结果
(
)
retain count = 2
retain count after the scope = 1
由此可知, Foundation 框架的 API 生成并持有的 Objective-C 对象能够作为 Core Foundation 对象来使用. 也可以通过 CFRelease 来释放. 当然, 也可以使用 __bridge_retained 转换来替代 CFBridgingRetain.
CFMutableArrayRef cfObject = (__bridge_retained CFMutableArrayRef)obj;
使用 __bridge 转换来替代 CFBridgingRetain 或 __bridge_retained 转换时, 源代码会变成什么样呢?
__bridge 转换不改变对象的持有状况, 所以将产生悬垂指针以下为用 __bridge 转换替代 CFBridgingRelease 或 __bridge_transfer 转换的情形
内存泄漏央
网友评论