首先看一下典型的NSString與CFStringRef的相互轉(zhuǎn)換
// CFStringRef to NSString *
NSString *yourFriendlyNSString = (__bridge NSString *)yourFriendlyCFString;
// NSString * to CFStringRef
CFStringRef yourFriendlyCFString = (__bridge CFStringRef)yourFriendlyNSString;
上面出現(xiàn)了一個關(guān)鍵字 __bridge 碍脏,這個關(guān)鍵字便是整個轉(zhuǎn)換的關(guān)鍵梭依。Apple官方對于 __bridge 的解釋如下:
**__bridge** transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.
**__bridge_retained** or **CFBridgingRetain** casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you. You are responsible for calling CFRelease or a related function to relinquish ownership of the object.
**__bridge_transfer** or **CFBridgingRelease** moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC. ARC is responsible for relinquishing ownership of the object.
上面這些話總結(jié)起來就是:
__bridge 用于Objective-C和Core Foundation指針之間的轉(zhuǎn)換,這種轉(zhuǎn)換不會更換對象的所有權(quán)(ownership)典尾。
__bridge_retained 或 CFBridgeRetain 用于從Objective-C到Core Foundation的指針轉(zhuǎn)換役拴,并且會將對象的所有權(quán)(ownership)轉(zhuǎn)移,所以你需要在不再使用該對象的時候調(diào)用CFRelease方法來解除引用钾埂。
__bridge_transfer 或 CFBridgeRelease 用于將非Objective-C指針轉(zhuǎn)換為Objective-C指針河闰,對象的所有權(quán)(ownership)會交給ARC,這時你無須擔(dān)心對象何時釋放褥紫,交給ARC去做就好了姜性。
為什么在使用__bridge_retained進(jìn)行轉(zhuǎn)換時需要自己調(diào)用CFRelease來釋放對象,其實(shí)原因很簡單:Core Foundation的對象在ARC的管轄范圍之內(nèi)髓考。
下面是示例代碼:
// Don't transfer ownership. You won't have to call `CFRelease`
CFStringRef str =(__bridge CFStringRef)string;
// Transfer ownership (i.e. get ARC out of the way). The object is now yours and you must call `CFRelease` when you're done with it
CFStringRef str =(__bridge_retained CFStringRef)string; // you will have to call `CFRelease`
// Don't transfer ownership. ARC stays out of the way, and you must call `CFRelease` on `str` if appropriate (depending on how the `CFString` was created)
NSString*string =(__bridge NSString*)str;
// Transfer ownership to ARC. ARC kicks in and it's now in charge of releasing the string object. You won't have to explicitly call `CFRelease` on `str`
NSString*string =(__bridge_transfer NSString*)str;
原文: http://www.outflush.com/nsstring-pointer-and-cfstringref-conversion-in-arc/
參考:http://blog.csdn.net/fightingbull/article/details/8098133