1

我确信有一种方法可以使用块来做到这一点,但我无法弄清楚。我想将 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];
4

3 回答 3

6

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

NSMutableArray* parametersArray = [[[NSMutableArray alloc] init] autorelease];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:@"&"];
于 2010-10-08T11:43:53.090 回答
2
NSMutableString* yourString = @"";

for (id key in dict) {
     [yourString appendFormat:@"%@=%@&", key, ((NSString*)[dict objectForKey:key])];
}

NSRange r;
r.location = 0;
r.size = [yourString length]-1;
[yourString deleteCharactersInRange:r];
于 2010-10-08T09:45:43.630 回答
2

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.

于 2010-10-08T09:40:25.340 回答