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.
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);
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];
}
You can use the description
method inherited by NSDictionary
from NSObject
, or write a custom method that formats NSDictionary
to your liking.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With