[Objective-C]ARC中NSString *與CFStringRef的相互轉換

##[Objective-C]ARC中NSString *與CFStringRef的相互轉換app

首先看一下典型的NSString與CFStringRef的相互轉換ui

// CFStringRef to NSString *
NSString *yourFriendlyNSString = (__bridge NSString *)yourFriendlyCFString;

// NSString * to CFStringRef
CFStringRef yourFriendlyCFString = (__bridge CFStringRef)yourFriendlyNSString;

上面出現了一個關鍵字 __bridge ,這個關鍵字即是整個轉換的關鍵。Apple官方對於 __bridge 的解釋以下:指針

__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.code

__bridge 用於Objective-C和Core Foundation指針之間的轉換,這種轉換不會更換對象的全部權(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.ip

__bridge_retained 或 CFBridgeRetain 用於從Objective-C到Core Foundation的指針轉換,而且會將對象的全部權(ownership)轉移,因此你須要在再也不使用該對象的時候調用CFRelease方法來解除引用。ci

__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.get

__bridge_transfer 或 CFBridgeRelease 用於將非Objective-C指針轉換爲Objective-C指針,對象的全部權(ownership)會交給ARC,這時你無須擔憂對象什麼時候釋放,交給ARC去作就行了。string

爲何在使用 __bridge_retained 進行轉換時須要本身調用CFRelease來釋放對象,其實緣由很簡單:Core Foundation的對象在ARC的管轄範圍以內。it

下面是示例代碼:

// 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;
相關文章
相關標籤/搜索