views:

49

answers:

3

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];
+1  A: 

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.

jer
+1  A: 
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];
MathieuF
+2  A: 

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:@"&"];
Benoît
FRotthowe
Exact ! Thank you ! (who invent copy/paste ?)
Benoît