Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 424
C.Johns Avatar asked Apr 12 '12 00:04

C.Johns


4 Answers

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);
like image 107
Jay Wardell Avatar answered Oct 17 '22 04:10

Jay Wardell


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];
}
like image 34
Danial Hussain Avatar answered Oct 17 '22 04:10

Danial Hussain


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

like image 38
Sergey Kalinichenko Avatar answered Oct 17 '22 03:10

Sergey Kalinichenko


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

like image 25
aliozkara Avatar answered Oct 17 '22 05:10

aliozkara