gpt4 book ai didi

objective-c - 如何在 ARC 中使用 CFMutableDictionaryRef

转载 作者:太空狗 更新时间:2023-10-30 03:58:21 24 4
gpt4 key购买 nike

这是你应该如何将 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

最佳答案

不要在这里使用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 进行平衡;您不必使用 CFBridgingRelease 除非您需要它返回的 id。同样,您可以平衡 CFRetainCFBridgingRelease

关于objective-c - 如何在 ARC 中使用 CFMutableDictionaryRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com