2009-06-15 108 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。 */

但是,如果您知道或可以验证您没有传递二进制格式,这应该没有问题。