Convert NSString to NSDictionary

Is there a way to return an NSDictionary from a string created using the 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); 

What makes this conclusion:

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

Is there an easy way to get back from a string in an NSDictionary?

+4
source share
4 answers

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

+5
source

The short answer is no. The description text is intended to quickly describe the contents of the dictionary, usually for debugging purposes.

It may 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 will not work. If, for example, your original dictionary contained any user data types, the description output would look something like this:

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

This, of course, is not reversible.

From the Apple developer documentation for the description method in NSDictionary :

If each key in the receiver is an NSString object, the records are listed in ascending order by key, otherwise the order in which the records are listed is undefined. This method is intended to create readable results for debugging purposes, and not to serialize data. If you want to save dictionary data for later retrieval, see the Property List Programming Guide and Cocoa Programming and Serialization Guide .

+5
source
  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"]); 

Please note that Apple reports

/ * These methods are no longer recommended because they do not work with property lists and string files in binary plist format. Use the API in NSPropertyList.h instead. * /

However, if you know or can confirm that you are not transmitting the binary format, this should work without problems.

+2
source

I don’t think it exists, you can write a method yourself, listing the contents of the string, this looks like a pretty simple format.

+1
source

Source: https://habr.com/ru/post/1286254/


All Articles