使用块将NSDictionary转换为字符串? [英] Turning a NSDictionary into a string using blocks?

查看:89
本文介绍了使用块将NSDictionary转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定有一种使用块的方法,但是我无法弄清楚.我想将NSDictionary转换为url样式的参数字符串. 如果我的NSDictionary看起来像这样:

I'm sure there is a way to do this using blocks, but I cant figure it out. I want to to turn an NSDictionary into url-style string of parameters. If I have an NSDictionary which looks like this:

dict = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"color", @"large", @"size", nil]];

然后我如何将其转换为如下所示的字符串:

Then how would I turn that into a string that looks like this:

"color=blue&size=large"


编辑

感谢以下线索.这应该做到:

Thanks for the clues below. This should do it:

NSMutableString *parameterString;
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [parameterString appendFormat:@"%@=%@&", key, obj];
}];
parameterString = [parameterString substringToIndex:[string length] - 1];

推荐答案

完全相同的解决方案,但没有子字符串:

Quite same solution but without the substring:

NSMutableArray* parametersArray = [[[NSMutableArray alloc] init] autorelease];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:@"&"];

这篇关于使用块将NSDictionary转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆