ios 将 NSDictionary 转换为 NSString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10116012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert NSDictionary to NSString
提问by C.Johns
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?
我试图将 NSDictionary 的内容放入 NSString 进行测试,但不知道如何实现这一点。是否可以?如果是这样,人们将如何做这样的事情?
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.
我这样做的原因是,我需要在没有调试器在我的设备上运行的情况下检查 NSDicitonary 的内容。因为我必须从 ios 的多任务栏中删除正在运行的应用程序,所以我可以查看我保存到字典中的值之后是否仍然可用。
回答by Jay Wardell
You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:
您可以调用 [aDictionary description] 或任何需要格式字符串的地方,只需使用 %@ 来代替字典:
[NSString stringWithFormat:@"my dictionary is %@", aDictionary];
or
或者
NSLog(@"My dictionary is %@", aDictionary);
回答by Danial Hussain
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];
}
回答by dasblinkenlight
You can use the description
method inherited by NSDictionary
from NSObject
, or write a custom method that formats NSDictionary
to your liking.
您可以使用从 fromdescription
继承的方法,或者编写一个自定义的方法来设置您喜欢的格式。NSDictionary
NSObject
NSDictionary