标签:
Core Foundation框架和Foundation框架有很多数据类型是可以相互转换的,这种能力叫做toll-free bridging。这意味着你可以使用同一种类型的数据作为Core Foundation函数调用的参数,同时作为Objective-C消息的返回值。例如NSLocale对应CFLocaleRef,但是并非所有的数据类型都是toll-free bridged,即使它们的名字显得它们似乎是可以的。例如NSRunLoop和CFRunLoop,NSBundle和CFBundle,NSDateFormatter和CFDateFormatter。
转换时需要给编译器提供以下信息:
编译器并不会自动管理Core Foundation对象的生命周期,你需要使用类型强制转换或者Core Foundation样式的宏来告诉编译器对象的所有权语义。
不交付所有权,只在Objective-C和Core Foundation 之间转换指针
将Objective-C指针交付给Core Foundation,同时将所有权转移给Core Foundation,必须调用CFRelease或者相关的函数来释放所有权
将非Objective-C指针交付给Objective-C,同时将所有权转移给ARC
tips:Core Foundation中凡是copy create之类的关键词的,要注意Release,同时转换成OC时要注意__bridge_transfer或者CGBridgingRelease()
示例1:
1 NSLocale *gbNSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; 2 CFLocaleRef gbCFLocale = (__bridge CFLocaleRef)gbNSLocale; 3 CFStringRef cfIdentifier = CFLocaleGetIdentifier(gbCFLocale); 4 NSLog(@"cfIdentifier: %@", (__bridge NSString *)cfIdentifier); 5 // Logs: "cfIdentifier: en_GB" 6 CFLocaleRef myCFLocale = CFLocaleCopyCurrent(); 7 NSLocale *myNSLocale = (NSLocale *)CFBridgingRelease(myCFLocale); 8 NSString *nsIdentifier = [myNSLocale localeIdentifier]; 9 CFShow((CFStringRef)[@"nsIdentifier: " stringByAppendingString:nsIdentifier]); 10 // Logs identifier for current locale
示例2:
1 - (void)drawRect:(CGRect)rect { 2 CGContextRef ctx = UIGraphicsGetCurrentContext(); 3 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 4 CGFloat locations[2] = {0.0, 1.0}; 5 NSMutableArray *colors = [NSMutableArray arrayWithObject:(id)[[UIColor darkGrayColor] CGColor]]; 6 [colors addObject:(id)[[UIColor lightGrayColor] CGColor]]; 7 CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations); 8 CGColorSpaceRelease(colorSpace); // Release owned Core Foundation object. 9 10 CGPoint startPoint = CGPointMake(0.0, 0.0); 11 CGPoint endPoint = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMaxY(self.bounds)); 12 CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint,kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation); 13 CGGradientRelease(gradient); // Release owned Core Foundation object. 14 }
Toll-Free Brige:解决Foundation与Core Foundation之间的类型转换
标签:
原文地址:http://www.cnblogs.com/sunnyfeng/p/4484121.html