標籤:des style io ar 使用 java for sp div
使用ARC能幫我們減輕不少記憶體管理方面的負擔,尤其是對用慣了Java的程式員來說。
最近,在做擷取本地通訊錄時,遇到CFObject和NSObject轉換的問題,由於ARC不能管理Core Foundation Object的生命週期,所以在Core Foundation和ARC之間,我們需要使用到__bridge,__bridge_retained和__bridge_transfer三個轉換關鍵字。
在蘋果官方文檔,我們找到了:
If you cast between Objective-C and Core Foundation-style objects, you need to tell the compiler about the ownership semantics of the object using either a cast (defined in objc/runtime.h
) or a Core Foundation-style macro (defined in NSObject.h
):
__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.
__bridge只做類型轉換,但是不修改對象(記憶體)管理權;
__bridge_retained(也可以使用CFBridgingRetain)將Objective-C的對象轉換為Core Foundation的對象,同時將對象(記憶體)的管理權交給我們,後續需要使用CFRelease或者相關方法來釋放對象;
__bridge_transfer(也可以使用CFBridgingRelease)將Core Foundation的對象轉換為Objective-C的對象,同時將對象(記憶體)的管理權交給ARC。
例如:
- (void)logFirstNameOfPerson:(ABRecordRef)person { |
|
NSString *name = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty); |
NSLog(@"Person‘s first name: %@", name); |
[name release]; |
} |
我們可以做這樣的修改:
- (void)logFirstNameOfPerson:(ABRecordRef)person { |
|
NSString *name = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty)); |
NSLog(@"Person‘s first name: %@", name); |
} |
Objective-C 學習筆記<二>