【问题标题】:How to use CFMutableDictionary with char array as key and integer as value?如何使用 CFMutableDictionary 与 char 数组作为键和整数作为值?
【发布时间】:2010-11-03 12:43:59
【问题描述】:

我正在使用现有的 iPhone 应用程序,同时需要更改 C 的代码。

我想在标准 C 文件中使用字典,简单地说,我不能使用 NSDictionary,编译器说它在 c99 中无效(因为找不到头文件 Foundation/Foundation.h 和 Foundation/NSDictionary.h),但是 CFDictionaryRef 是可用的(可以找到并导入头文件 CoreFoundation/CoreFoundation.h)。然后我尝试使用 CFDictionary,我无法将键值对插入字典中,有人可以花点时间看看下面的代码吗?提前致谢!!

ps,下面代码的输出是:

字典大小:0 键:text.html,值:111

表示没有插入键值对...


CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

printf("Dict size: %d\n", (int)((CFIndex)CFDictionaryGetCount(dict)));

int i = 111;
char c[] = "text.html";

const void *key = &c;
const void *value = &i;

printf("Key: %s, value: %d\n", key, *(int *)value);

CFDictionarySetValue(dict, key, value); 

printf("Added\n");

printf("Dict size: %d\n", (int)((CFIndex)CFDictionaryGetCount(dict)));

value = (int *)CFDictionaryGetValue(dict, key);

printf("Value:  %d\n", *(int *)value);

感谢您的输入,以下是工作代码。


//初始化字典 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    //insert key-value
int i = 111;
const void *value = &i;
CFDictionaryAddValue(dict, CFSTR("text.html"), CFNumberCreate(NULL, kCFNumberSInt32Type, value));
CFNumberRef valueRef = CFDictionaryGetValue(dict, CFSTR("text.html"));

    //get value based on key
int valuePtr;
CFNumberGetValue(valueRef, kCFNumberSInt32Type, (void *)&valuePtr);
    printf("value: %d\n", valuePtr);

【问题讨论】:

    标签: iphone xcode iphone-sdk-3.0 ios4 core-foundation


    【解决方案1】:

    使用&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks 作为参数创建的CFMutableDictionaryRef 期望Core Foundation 类型作为键和值,因为它将尝试保留/释放它们(使用CFRetain/CFRelease)。

    您应该使用CFStringRefCFNumberRef 而不是普通的C 类型(或者,指定其他keyCallBacksvalueCallBacks,可能是NULL)。

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 2022-10-18
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多