我敢肯定有一种使用块的方法,但是我无法弄清楚。我想将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];
最佳答案
完全相同的解决方案,但没有子字符串:
NSMutableArray* parametersArray = [[[NSMutableArray alloc] init] autorelease];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:@"&"];
关于iphone - 使用 block 将NSDictionary转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3889337/