views:

1145

answers:

3

Is there a way to get an NSDictionary back from the string created via its description method?

Given this code:

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);

Which makes this output:

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

Is there an easy way to go back from the string to an NSDictionary?

+1  A: 

I don't think there is one, you can write a method yourself through, by enumerating through the contents of a string, it looks like a pretty easy format to go through.

Suvesh Pratapa
Not a great idea. Although the format appears simple with this code, you can't always count on the quotes or even the exact format shown.
Quinn Taylor
+2  A: 

At the risk of asking a stupid question: why would you want to do this? If you want to go to and from text, use the NSPropertyListSerialization class.

Ben Gottlieb
I typed this up just as a clear example of the string i am trying to parse. Truth be told the "Dictionary String" is coming from a 3.0 API and not my code. I thought there might be a simple way to parse it.
Lounges
Perhaps it's actually a property list in OpenStep format (that's what -[NSDictionary description] is, except it allows non-property-list objects). Try NSPropertyListSerialization with that format.
Peter Hosey
This worked great. Thank you.
Lounges
+4  A: 

The short answer is no. The description text is intended to be a quick description of the contents of the dictionary, usually for debugging purposes.

It might be possible (but not recommended) to parse the output string and use it to populate a new dictionary, but there are many cases where this would not work. If, for example, your original dictionary contained any custom data types, the description output would appear something like:

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

Which is, of course, not reversible.

From Apple's developer documentation for the description method in 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.

e.James