使用块将 NSDictionary 转换为字符串?
我确信有一种方法可以使用块来做到这一点,但我无法弄清楚。我想将 NSDictionary 转换为 url 样式的参数字符串。 如果我有一个如下所示的 NSDictionary:
dict = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"color", @"large", @"size", nil]];
那么我如何将其转换为如下所示的字符串:
"color=blue&size=large"
编辑
感谢以下线索。这应该可以做到:
NSMutableString *parameterString;
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[parameterString appendFormat:@"%@=%@&", key, obj];
}];
parameterString = [parameterString substringToIndex:[string length] - 1];
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"
EDIT
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
完全相同的解决方案,但没有子字符串:
Quite same solution but without the substring:
创建一个可变字符串,然后迭代字典获取每个键。查找该键的值,并将
key=value&
添加到字符串中。完成该循环后,删除最后一个 &。我认为这将通过 URL 提供,您还需要一些对字符串进行编码的方法,以防它们包含类似 & 的项目。或+等
Create a mutable string, then iterate the dictionary getting each key. Look up the value for that key, and add the
key=value&
to the string. When you finish that loop, remove the last &.I presume this is going to be fed through a URL, you will also want to have some method that encodes your strings, in case they contain items like & or +, etc.