【发布时间】: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