2010-11-03 52 views
0

我正在使用現有的iPhone應用程序,同時需要更改C代碼。如何使用CFMutableDictionary與char數組作爲鍵和整數值?

我想在標準C文件中使用字典,簡單地說,我不能使用NSDictionary,編譯器表示它在c99中無效不能找到頭文件Fou​​ndation/Foundation.h和Foundation/NSDictionary.h),但CFDictionaryRef可用(可以找到並導入coz頭文件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字典= 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); 

回答

1

一個CFMutableDictionaryRef&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks創建作爲參數預計核心基礎類型作爲鍵和值,因爲它會嘗試保留/釋放他們(使用CFRetain/CFRelease)。

你應該工作與CFStringRefCFNumberRef代替普通的C類型(或可替代地,指定其他keyCallBacksvalueCallBacks,可能NULL)。

+0

謝謝,它適用於CFStringRef和CFNumberRef – CCTV 2010-11-03 14:21:36

相關問題