void *与id类型的相互转换
void *与id类型相互转换
在MRC下,void *与id类型相互转换完全没问题。
id obj = [[NSObject alloc] init]; void *p = (void *)p; obj = (id)p;
但是在ARC下,这种直接转换编译器会报错,需要使用__bridge关键字:
id obj = [[NSObject alloc] init]; //引用计数为1 void *p = (__bridge void *)obj; //引用计数仍为1 id obj2 = (__bridge id)p ;// 引用计数为2,因为obj2是__strong
__bridge_retained与__bridge_transfer
与__bridge相关的还有另外两个:__bridge_retained和__bridge_transfer。
id obj = [[NSObject alloc] init]; //引用计数为1 void *p = (__bridge_retained void *)obj ;// 引用计数为2 //上述代码等价在MRC为 id obj = [[NSObject alloc] init]; [obj retain]; void *p = (__bridge void)obj
id obj = (__bridge_transfer id)p //引用计数仍为1 //上述代码等价在MRC为id obj obj = (__bridge id)p [obj retain]; [(id)p release];
CFBridgingRetain与CFBridgingTransfer
这两个函数也只在ARC下生效,等价于:
CFTypeRef CFBridgingRetain(id X) { return (__bridge_retained CFTypeRef)X; } id CFBridgingRelease(CFTypeRef X) { return (__bridge_transfer id)X; }