这是你应该如何在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
答案 0 :(得分:11)
此处不要使用CFBridgingRetain
和CFBridgingRelease
。此外,在投射__bridge
的结果时,您需要使用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);
不需要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
平衡;您不必使用CFBridgingRelease
,除非您需要它返回的id
。同样,您可以平衡CFRetain
和CFBridgingRelease
。