How to use CFMutableDictionaryRef with ARC

Is this how you should use CFMutableDictionaryRef with ARC?

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 
+4
source share
1 answer

Do not use CFBridgingRetain and CFBridgingRelease here at all. In addition, you need to use __bridge when CFDictionaryGetValue result of CFDictionaryGetValue .

 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); 

There is no need for CFBridgingRetain , because the dictionary will still keep the value. And if you do not call CFBridgingRetain , you do not need to balance it with the release later.

In any case, this is much simpler if you just create an NSMutableDictionary , and then if you need CFMutableDictionary , produce it:

 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); 

Note that a CFBridgingRetain can be balanced with CFRelease ; you do not need to use CFBridgingRelease unless you need the id that it returns. Similarly, you can balance CFRetain with CFBridgingRelease .

+11
source

Source: https://habr.com/ru/post/1399563/


All Articles