码迷,mamicode.com
首页 > 其他好文 > 详细

Toll-Free Brige:解决Foundation与Core Foundation之间的类型转换

时间:2015-05-07 11:46:08      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

Core Foundation框架和Foundation框架有很多数据类型是可以相互转换的,这种能力叫做toll-free bridging。这意味着你可以使用同一种类型的数据作为Core Foundation函数调用的参数,同时作为Objective-C消息的返回值。例如NSLocale对应CFLocaleRef,但是并非所有的数据类型都是toll-free bridged,即使它们的名字显得它们似乎是可以的。例如NSRunLoop和CFRunLoop,NSBundle和CFBundle,NSDateFormatter和CFDateFormatter。

转换时需要给编译器提供以下信息:

  • you have to cast one type to the other(类型强制转换)
  • you may have to indicate the object lifetime semantics(提供对象生命周期的语义)

编译器并不会自动管理Core Foundation对象的生命周期,你需要使用类型强制转换或者Core Foundation样式的宏来告诉编译器对象的所有权语义。

__bridge

不交付所有权,只在Objective-C和Core Foundation 之间转换指针

__bridge_retained / CFBridgingRetain

将Objective-C指针交付给Core Foundation,同时将所有权转移给Core Foundation,必须调用CFRelease或者相关的函数来释放所有权

__bridge_transfer / CGBridgingRelease

将非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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!