convert NSDictionary to NSString

I am trying to put the content of an NSDictionary into an NSString for testing, But have no idea how to achieve this. Is it possible? if so how would one do such a thing?

The reason I am doing this, Is I need to check the content of a NSDicitonary without the debugger running on my device. as I have to delete the running app from multitasking bar of the ios so I can see if the values I am saving into the dictionary are still available afterwards.


Solution 1:

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

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

or

NSLog(@"My dictionary is %@", aDictionary);

Solution 2:

Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.

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];
}

Solution 3:

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

Solution 4:

if you like to use for URLRequest httpBody

extension Dictionary {

    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }

}

// print: Fields=sdad&ServiceId=1222