2012-01-16 37 views
3

我想簡化一些鑰匙串服務代碼,並使用CFDictionarySetValue和Foundation的NSString如何在CoreFoundation函數中正確使用Foundation的NSString?

CFDictionarySetValue聲明是這樣說:

void CFDictionarySetValue(CFMutableDictionaryRef theDict, const void *key, const void *value) 

所以當我通過例如會發生什麼@"This is a NSString"value參數?在我的情況下,編譯器不報告警告,也不會靜態分析捕獲任何東西。在運行時,沒有崩潰,所以這意味着運行時需要處理所有事情,否則我應該通過[@"something" cStringUsingEncoding:NSUTF8StringEncoding]並將其轉換爲const void*

我的研究結果表明:

NSLog(@"%s", CFDictionaryGetValue(query, kKeyForCStringInUTF8)); 
NSLog(@"%@", CFDictionaryGetValue(query, kKeyForNSString)); 

都給出相同的輸出!它令人困惑...

CF和Foundation之間交換對象的一般規則是什麼?是否有普遍接受的代碼風格,是一種好的做法?

+0

好吧,我決定不「簡化」代碼正如我上面所建議的。對象互操作性是這樣做的,所以我可以堅持'NSMutableDictionary'。 – matm 2012-01-17 09:47:27

回答

3

NSString和其他類型的免費橋接到他們的CoreFoundation對應。
Core Foundation Design Concepts - Toll-Free Bridged Types

有在Core Foundation框架的一些數據類型和基礎框架,可以互換使用。這意味着您可以使用與Core Foundation函數調用的參數相同的數據結構,或者作爲Objective-C消息調用的接收方。

+0

我很高興這覆蓋了文檔:)感謝很多把這個文檔:) – matm 2012-01-17 07:09:01

1

我不確定你到底在問什麼,所以我打算擴大Georg的答案。我假設你需要CFMutableDictionaryRef,但你仍然可以使用MSMutableDictionary。如果這不是您的問題的答案,請告訴我。

如果我是你,我會簡單地使用NSMutableDictionary來代替,所以你可以簡單地使用[yourDictionary setValue:yourString forKey:@"yourKey"];。如果沒有其他的話,那就擺脫一個參數。如果您需要CFMutableDictionaryRef,只需使用此代碼:

CFMutableDictionaryRef cfDictionary = (CFMutableDictionaryRef) yourDictionary; 

那麼,來設置和獲取的價值,你可能只是這樣做:

// Make the objects somewhere 
NSString *yourString = @"something"; 
NSMutableDictionary *yourDictionary = [[NSMutableDictionary alloc] init]; 

// now set the value... 
[dictionary setObject:yourString forKey:@"Anything at all"]; 

// and to get the value... 
NSString *value = [yourDictionary valueForKey:@"Anything at all"]; 

// now you can show it 
NSLog(@"%@", value); 
+0

在我的情況下,我完全想用'CFMutableDictionaryRef'和'CFDictionarySetValue'來替換'NSMutableDictionary'操作,我會提高代碼的可讀性和緊湊性,但我知道,對於一些人來說,複雜性會增加......感謝您的貢獻! – matm 2012-01-17 07:08:12

相關問題