Convert NSDictionary to NSString

I am trying to put the contents of an NSDictionary in an NSString for testing, but have no idea how to achieve this. Is it possible? if so, how to do it?

The reason I do this is: do I need to check the contents of NSDictonary without debugging running on my device. since I have to remove the running application from the ios multitasking panel so that I can see if the values ​​that I save in the dictionary are saved.

+47
ios iphone nsstring nsdictionary
Apr 12 2018-12-12T00:
source share
3 answers

You can call [aDictionary description], or anywhere you need a format string, just use% @ to enter the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary]; 

or

 NSLog(@"My dictionary is %@", aDictionary); 
+115
Apr 12 2018-12-12T00:
source share

Above Solutions will only convert the dictionary to a string, but you cannot convert this string to a dictionary. This is the best way to do this.

Convert to string

 NSError * err; NSData * jsonData = [NSJSONSerialization dataWithJSONObject:yourDictionary options:0 error:&err]; NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@",myString); 

Convert back to dictionary

 NSError * err; NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary * response; if(data!=nil){ response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err]; } 
+49
Aug 11 '15 at 9:26
source share

You can use the description method inherited by NSDictionary from NSObject , or write your own method that formats the NSDictionary to your liking.

+12
Apr 12 2018-12-12T00:
source share



All Articles