如何在ARC下使用CFMutableDictionaryRef

4

这是使用CFMutableDictionaryRef和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
1个回答

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。同样地,您可以使用 CFBridgingRelease 平衡 CFRetain


我不应该使用CFBridgingRetain,因为CFDict会为我保留吗? - joels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接