如何在ARC中使用CFMutableDictionaryRef

joe*_*els 4 objective-c core-foundation automatic-ref-counting

这是你应该如何在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
Run Code Online (Sandbox Code Playgroud)

rob*_*off 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);
Run Code Online (Sandbox Code Playgroud)

没有必要,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);
Run Code Online (Sandbox Code Playgroud)

注意a CFBridgingRetain可以通过a平衡CFRelease; CFBridgingRelease除非你需要id它返回,否则你不必使用.同样,你可以平衡a CFRetain和a CFBridgingRelease.