ARC中NSString *與CFStringRef的相互轉(zhuǎn)換

首先看一下典型的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來釋放對象,其實原因很簡單: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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容