<pre name="code" class="objc">iOS允许Objective-C 和 Core Foundation 对象之间可以轻松的转换,拿 NSString 和 CFStringRef 来说,直接转换豪无压力
CFStringRef aCFString = (CFStringRef)aNSString; NSString *aNSString = (NSString *)aCFString;
针对内存管理问题,ARC 可以帮忙管理 Objective-C 对象, 但是不支持 Core Foundation 对象的管理,所以转换后要注意一个问题:谁来释放使用后的对象。 本文重点总结一下类型转换后的内存管理。
//NSString 转 CFStringRef CFStringRef aCFString = (CFStringRef) [[NSString alloc] initWithFormat:@"%@", string]; //... CFRelease(aCFString); //CFStringRef 转 NSString CFStringRef aCFString = CFStringCreateWithCString(kCFAllocatorDefault, bytes, NSUTF8StringEncoding); NSString *aNSString = (NSString *)aCFString; //... [aNSString release];
__bridge_retained 或者 CFBridgingRetain() (解除 ARC 所有权)
__bridge_transfer 或者 CFBridgingRelease() (
给予 ARC 所有权)- (void)viewDidLoad { [super viewDidLoad]; NSString *aNSString = [[NSString alloc]initWithFormat:@"test"]; CFStringRef aCFString = (__bridge_retained CFStringRef) aNSString; (void)aCFString; //正确的做法应该执行CFRelease //CFRelease(aCFString); }
CFStringRef aCFString = (__bridge_retained CFStringRef) aNSString; CFStringRef aCFString = (CFStringRef) CFBridgingRetain(aNSString);
- (void)viewDidLoad { [super viewDidLoad]; NSString *aNSString = [[NSString alloc]initWithFormat:@"test"]; CFStringRef aCFString = (__bridge_retained CFStringRef) aNSString; aNSString = (__bridge_transfer NSString *)aCFString; }
aNSString = (__bridge_transfer NSString *)aCFString; aNSString = (NSString *)CFBridgingRelease(aCFString);
- (void)viewDidLoad { [super viewDidLoad]; NSString *aNSString = [[NSString alloc]initWithFormat:@"test"]; CFStringRef aCFString = (__bridge CFStringRef)aNSString; (void)aCFString; }
- (void)viewDidLoad { [super viewDidLoad]; CFStringRef aCFString = CFStringCreateWithCString(NULL, "test", kCFStringEncodingASCII); NSString *aNSString = (__bridge NSString *)aCFString; (void)aNSString; CFRelease(aCFString); }