How to use CFMutableDictionary with char array as key and integer as value?
I am working an existing iPhone app, while need to change the code of C.
I want to use a dictionary in standard C file, simpily, I can not use NSDictionary, compiler said it is invalid in c99(coz the headers Foundation/Foundation.h and Foundation/NSDictionary.h can not be found), but CFDictionaryRef is available (coz header CoreFoundation/CoreFoundation.h can be found and imported). Then I try to work with CFDictionary, I can not insert the key-value pairs into the dictionary, could any one take a while and have a look at following code? Thanks in advance!!
ps, the output of following code are:
Dict size: 0 Key: text.html, value: 111
which means the key-value pair is not inserted...
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);
Thanks for your inputs, following are the working code.开发者_如何转开发
//init dict 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);
A CFMutableDictionaryRef
created with &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks
as arguments expects Core Foundation types as keys and values because it will try to retain/release them (using CFRetain
/CFRelease
).
You should work with CFStringRef
and CFNumberRef
instead of the plain C types (or alternatively, specify other keyCallBacks
and valueCallBacks
, possibly NULL
).
精彩评论