2009-06-15 113 views
4

有沒有辦法從通過其description方法創建的字符串中獲得NSDictionary將NSString轉換爲NSDictionary

鑑於此代碼:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value 1", @"value 2", nil] forKeys:[NSArray arrayWithObjects:@"key 1", @"key 2", nil]]; 
NSString *dictionaryString = [dictionary description]; 
NSLog(dictionaryString); 

這使得這款輸出:

{ 
    "key 1" = "value 1"; 
    "key 2" = "value 2"; 
} 

是否有一個簡單的方法來從字符串到一個NSDictionary回去?

+2

爲什麼不使用序列化而不是描述字段? – Kekoa 2009-06-15 21:46:14

+3

NSLog(dictionaryString);是一個安全問題。使用NSLog(@「%@」,dictionaryString);代替。如果dictionaryString包含字符%@,則您的應用程序會崩潰,或者顯示潛在的敏感信息。 – 2009-06-15 22:27:56

回答

5

冒着問一個愚蠢的問題:你爲什麼要這麼做?如果您想要往返文本,請使用NSPropertyListSerialization類。

1

我不認爲有一個,你可以自己寫一個方法,通過枚舉一個字符串的內容,它看起來像一個非常簡單的格式來通過。

+0

不是一個好主意。儘管使用此代碼格式顯得很簡單,但您不能始終依靠引號或甚至顯示的確切格式。 – 2009-06-16 05:54:09

5

簡短的回答是否定的。描述文本旨在簡要描述字典的內容,通常用於調試目的。

解析輸出字符串並將其用於填充新字典可能是可能的(但不推薦),但是在很多情況下這是行不通的。如果,例如,原來的字典包含的任何自定義數據類型,說明輸出將出現類似:

{ 
    "key 1" = <SomeClass 0x31415927>; 
    "key 2" = <SomeClass 0x42424242>; 
} 

哪個,當然,不可逆的。

從蘋果的開發者documentationdescription方法NSDictionary

If each key in the receiver is an NSString object, the entries are listed in ascending order by key, otherwise the order in which the entries are listed is undefined. This method is intended to produce readable output for debugging purposes, not for serializing data. If you want to store dictionary data for later retrieval, see Property List Programming Guide and Archives and Serializations Programming Guide for Cocoa .

2
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value 1", @"value 2", nil] forKeys:[NSArray arrayWithObjects:@"key 1", @"key 2", nil]]; 
    NSString *dictionaryString = [dictionary description]; 
    NSLog(@"%@", dictionaryString); 

    NSDictionary *d = [dictionaryString propertyList]; 
    NSLog(@"%@", [d objectForKey:@"key 2"]); 

注意,蘋果的文件說

/*不再推薦使用這些方法,因爲它們不與財產清單工作和二進制plist格式的字符串文件。請改用NSPropertyList.h中的API。 */

但是,如果您知道或可以驗證您沒有傳遞二進制格式,這應該沒有問題。