- __bridge,__bridge_retained,__bri
- __bridge , __bridge_transfer, __
- 理解__bridge,__bridge_transfer和__b
- Objective-C ARC 下 OC 对象和 CF 对象之间
- iOS-浅谈__bridge
- __bridge_retained 与 __bridge_tra
- _ _bridge,_ _bridge_retained 和 _
- __bridge_transfer __bridge_ret
- __bridge __bridge_transfer __bri
- __bridge、__bridge_retained和 __br
__bridge,__bridge_retained,__bridge_transfer用于OC类型和C类型的转换,其中__bridge只做转换,不涉及对象所有权的转化,__bridge_retained除了将OC类型转换为C类型外还会增加OC对象的引用计数,__bridge_transfer除了将C类型转换为OC类型外还会减少OC对象的引用计数。
下面代码中obj被ARC管理,testPointer是一个C语言指针,在obj脱离viewDidLoad作用域时就已经被销毁了,testButtonDidClick调用时会报错,而将__bridge改为__bridge_retained就不会了。
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic) void* testPointer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
id obj = [[NSObject alloc] init];
_testPointer=(__bridge void *)obj;
}
- (IBAction)testButtonDidClick:(id)sender {
NSLog(@"%@", [(__bridge id)_testPointer class]);
}
@end
_testPointer=(__bridge_retained void *)obj在非ARC环境下可以表示为下面的代码:
_testPointer=obj;
[(id)testPointer retain];
id obj=(__bridge_transfer id)_testPointer在非ARC环境下可以表示为下面的代码:
id obj = (id)_testPointer;
[obj retain];
[(id)_testPointer release];
在Core Foundation中使用CFRetain,CFRelease也可以起到和__bridge_retained,__bridge_transfer一样的效果。
//OC类型转C类型
_testPointer=(__bridge void*)obj;
CFRetain(_testPointer);
//C类型转OC类型
id obj=(__bridge id)_testPointer;
CFRelease(_testPointer);
网友评论