Apple參考文檔:參考文檔
橋接
在開發中時常要使用Core Foundation框架,例如Core Graphics、Core Text等,有時需要在CF指針和OC對象之間進行轉換,,在轉換中需要注意內存管理。在ARC環境下,編譯器不能自動管理CF對象的內存,我們需要使用CFRelease將其手動釋放。因此需要時可以使用 __bridge
__bridge_transfer
__bridge_retained
進行橋接。
使用方法
-
__bridge
:CF和OC對象轉化時只涉及對象類型不涉及對象所有權的轉化
NSURL *url = [[NSURL alloc] initWithString:@"http://www.baidu.com"];
CFURLRef ref = (__bridge CFURLRef)url;
使用 __bridge
時,不管是從OC轉換到CF還是從CF轉換成OC,即內存的管理權(所有權)不隨轉換而轉換,CF對象還是需要使用CFRelease(),OC對象由ARC自動管理。
-
__bridge_transfer
orCFBridgingRelease
:在CF指針轉換成OC對象時,將CF指針的所有權交給ARC管理,此時ARC就能自動管理該內存
-
__bridge_retained
orCFBridgingRetain
:將OC對象轉換成CF指針時,管理的所有交由使用者手動釋放
NSURL *url = [[NSURL alloc] initWithString:@"http://www.baidu.com"];
CFURLRef ref = (__bridge_retained CFURLRef)url;
CFRelease(ref);
綜合示例
NSLocale *gbNSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
CFLocaleRef gbCFLocale = (__bridge CFLocaleRef)gbNSLocale;
CFStringRef cfIdentifier = CFLocaleGetIdentifier(gbCFLocale);
NSLog(@"cfIdentifier: %@", (__bridge NSString *)cfIdentifier);
// Logs: "cfIdentifier: en_GB"
CFLocaleRef myCFLocale = CFLocaleCopyCurrent();
NSLocale *myNSLocale = (NSLocale *)CFBridgingRelease(myCFLocale);
NSString *nsIdentifier = [myNSLocale localeIdentifier];
CFShow((CFStringRef)[@"nsIdentifier: " stringByAppendingString:nsIdentifier]);
// Logs identifier for current locale
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGFloat locations[2] = {0.0, 1.0};
NSMutableArray *colors = [NSMutableArray arrayWithObject:(id)[[UIColor darkGrayColor] CGColor]];
[colors addObject:(id)[[UIColor lightGrayColor] CGColor]];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);
CGColorSpaceRelease(colorSpace); // Release owned Core Foundation object.
CGPoint startPoint = CGPointMake(0.0, 0.0);
CGPoint endPoint = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMaxY(self.bounds));
CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint,
kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
CGGradientRelease(gradient); // Release owned Core Foundation object.
}
類型轉換列表

轉換列表