2012-03-03 59 views
4

這是你應該如何使用CFMutableDictionaryRef和ARC?如何使用帶有ARC的CFMutableDictionaryRef

CFMutableDictionaryRef myDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 
NSString *key = @"someKey"; 
NSNumber *value = [NSNumber numberWithInt: 1]; 
//ARC doesn't handle retains with CF objects so I have to specify CFBridgingRetain when setting the value 
CFDictionarySetValue(myDict, (__bridge void *)key, CFBridgingRetain(value)); 
id dictValue = (id)CFDictionaryGetValue(myDict, (__bridge void *)key); 
//the value is removed but not released in any way so I have to call CFBridgingRelease next 
CFDictionaryRemoveValue(myDict, (__bridge void *)key); 
CFBridgingRelease(dictValue);//no leak 

回答

11

不要使用CFBridgingRetainCFBridgingRelease這裏都沒有。另外,在投射CFDictionaryGetValue的結果時,您需要使用__bridge

CFMutableDictionaryRef myDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 
NSString *key = @"someKey"; 
NSNumber *value = [NSNumber numberWithInt: 1]; 
CFDictionarySetValue(myDict, (__bridge void *)key, (__bridge void *)value); 

id dictValue = (__bridge id)CFDictionaryGetValue(myDict, (__bridge void *)key); 
CFDictionaryRemoveValue(myDict, (__bridge void *)key); 

沒有必要爲CFBridgingRetain因爲字典無論如何都會保留價值。如果你不打電話CFBridgingRetain,你不需要在稍後的版本中平衡它。

無論如何,這是所有要簡單得多,如果你只是建立一個NSMutableDictionary然後,如果你需要一個CFMutableDictionary,將其丟:

NSMutableDictionary *myDict = [NSMutableDictionary dictionary]; 
NSString *key = @"someKey"; 
NSNumber *value = [NSNumber numberWithInt: 1]; 
[myDict setObject:value forKey:key]; 

CFMutableDictionaryRef myCFDict = CFBridgingRetain(myDict); 
// use myCFDict here 
CFRelease(myCFDict); 

注意,一個CFBridgingRetain可以通過CFRelease來平衡;除非您需要返回的id,否則不必使用CFBridgingRelease。同樣,您可以將CFRetainCFBridgingRelease平衡。

+0

我不應該使用CFBridgingRetain,因爲CFDict會保留我嗎? – joels 2012-03-06 14:50:34